<?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 Narendra Pal on Medium]]></title>
        <description><![CDATA[Stories by Narendra Pal on Medium]]></description>
        <link>https://medium.com/@npcoder2k14?source=rss-93c26ced7936------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*JSOG9in029c7hWdaQY5IDw.jpeg</url>
            <title>Stories by Narendra Pal on Medium</title>
            <link>https://medium.com/@npcoder2k14?source=rss-93c26ced7936------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 16:52:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@npcoder2k14/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[Understanding and Managing dhandles in MongoDB]]></title>
            <link>https://medium.com/helpshift-engineering/understanding-and-managing-dhandles-in-mongodb-8c5d5a2eaf3f?source=rss-93c26ced7936------2</link>
            <guid isPermaLink="false">https://medium.com/p/8c5d5a2eaf3f</guid>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Narendra Pal]]></dc:creator>
            <pubDate>Wed, 20 Sep 2023 09:53:02 GMT</pubDate>
            <atom:updated>2023-09-20T09:53:02.300Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V0jDw33D3FryrMsVvzRq4Q.png" /></figure><h3>Introduction</h3><p>This article is about a less talked MongoDB entity called <strong>dhandles</strong> or <strong>data handles </strong>and how this entity can affect MongoDB’s stability and performance.</p><p>For context, Helpshift is a customer support conversational platform. Our customers can integrate our SDKs with their applications to interact with their users via tickets.</p><p>This story is about problems we faced with MongoDB in the year 2020. The data is from the same time.</p><p>We use MongoDB at Helpshift. We had the following average RPS</p><ol><li>Reads — 3.6k per second</li><li>Writes — 280 per second</li></ol><p>We had a replica-set MongoDB setup with the following specifications —</p><pre><br>+---------------+------------+<br>|     Specs     |   value    |<br>+---------------+------------+<br>| Instance type | i3 8xlarge |<br>| CPUs          | 32         |<br>| RAM           | 244 GB     |<br>| Replica       | 4 - 6      |<br>+---------------+------------+<br><br></pre><p>We had more than 2TB of data.</p><h3>Signs of Trouble</h3><p>In 2020, we started experiencing problems with MongoDB.<br>During this time, we started seeing occasional read and write failures.<br>The failures would occur in a flurry for 15–30 seconds and then stop. We ended up in an inconsistent state in our critical business objects, e.g. tickets.<br>For example, a ticket is created without any message.</p><blockquote>The term support ticket refers to a type of interaction between a customer support team and a customer. Tickets can be opened by customers whenever they have an issue. Customers can chat with the support agent to resolve their problems.<br>Source — <a href="https://www.helpshift.com/glossary/what-is-a-support-ticket/">https://www.helpshift.com/glossary/what-is-a-support-ticket/</a></blockquote><p>With some analysis of MongoDB graphs, we could correlate these errors with increasing checkpointing time. We started seeing an uptick in checkpointing time around the same time as when we began facing the issue. <br>It was nearing 60 seconds compared to the normal 10 seconds. Hence, the subsequent checkpointing event was delayed, leading to accumulated dirty bytes for the next checkpointing event.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SiOCqRvQ-dPFsmMDP2tPLA.png" /><figcaption>Increase in checkpointing time for MongoDB server in 6 months (from ~10s to ~30s):</figcaption></figure><blockquote>Checkpointing in databases refers to the process of periodically saving the current state of the database to disk. It involves writing modified data from memory (RAM) to the database’s permanent storage, typically a hard disk or solid-state drive (SSD).</blockquote><p>MongoDB uses the <a href="https://www.mongodb.com/docs/manual/core/wiredtiger/">WiredTiger storage engine</a>. During checkpointing, the WiredTiger storage engine flushes dirty bytes from the cache to disk, hence application read/writes requests are queued or failed in worst cases.</p><p>This was a huge problem.</p><h3>The Hidden Villain: Dhandles Revealed</h3><p>As a temporary solution, we used to do a rolling restart of the MongoDB cluster. This activity temporarily lowered the checkpointing time and increased the overall health of MongoDB. But this was a temporary solution.<br>The checkpointing time would again increase after a few months. We realized we still didn’t know the root cause of why the checkpointing time was increasing.</p><p>Time was of the essence here because our customers were getting impacted. So, we opted for a MongoDB consulting session to find the root cause of the issue. In this session, the MongoDB consultant collected multiple pieces of information from us like Reads/writes per second, dataset size, and our data model.</p><p>During these sessions, we also talked about how we designed databases for our customers. We used to create a dedicated database for every customer with respective business entity collections in it. This design led to us having around 2200+ databases with around 50 collections in each. We got to know that this might be the problem. This was an inefficient way to model data.</p><p>The WiredTiger maintains an entity called dhandle or data handle per data source for reading and writing to them. Checkpointing process iterates through all dhandles, hence a high number of dhandles can increase the checkpointing time.<br>We started seeing these problems after moving from <a href="https://www.mongodb.com/docs/v4.0/core/mmapv1/">MMAPv1</a> to the WiredTiger storage engine.<br>We were onto something with this new information.</p><h4>What are dhandles?</h4><p>From the WiredTiger documentation,</p><blockquote>Dhandle is a generic representation of any named data source. Dhandles are required to access any data source in the system. WiredTiger maintains all dhandles in a global list accessed by sessions. Dhandles are created when accessing tables and other data sources that have not been accessed before.<br>Source — <a href="https://source.wiredtiger.com/11.0.0/arch-dhandle.html">https://source.wiredtiger.com/11.0.0/arch-dhandle.html</a></blockquote><p><strong><em>Now the question is what are these named data sources?<br></em></strong>They can be databases, collections or indices.<br>It means —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/428/1*U12nvDYWFdujrT_74Y1s0A.png" /></figure><p><strong>Dhandles count calculation</strong></p><p>Let’s calculate dhandles count for our MongoDB instance. Following are the details about our data model —</p><pre><br>+-------------+---------------------+<br>|    Specs    |        Value        |<br>+-------------+---------------------+<br>| Databases   | 2200+               |<br>| Collections | 50 per database     |<br>| Indices     | 2.45 per collection |<br>+-------------+---------------------+<br><br></pre><p>Using the above information, max possible dhandles count —</p><p>2200 (databases count) + 2200*50 (collections count) + 2.45*2200*50 (indices count) = 3,81,700</p><p>The above number is the max possible dhandles. Fortunately, the actual dhandles count was ~1,65,000 in our case because we also had data for inactive customers which wasn’t getting accessed at all.<br>You can get this count via the <a href="https://www.mongodb.com/docs/manual/reference/command/serverStatus/">serverStatus</a> command in MongoDB shell —</p><pre>db.serverStatus()[&#39;wiredTiger&#39;][&#39;data-handle&#39;][&#39;connection data handles currently active&#39;]</pre><p>From our consulting sessions, we got to know max recommended limit for dhandles is 20,000. We had ~1,65,000 dhandles against the recommended limit of just 20,000!<br>Also, this dhandles count was unbounded due to having a dedicated database for each customer. With each new customer, this count will keep increasing, in turn deteriorating MongoDB’s health.</p><h3>Solutions</h3><p>With this new knowledge, we started brainstorming solutions to lower the dhandles count. We planned to implement solutions in two phases —</p><h4>Mitigation: stop dhandles growth</h4><p>There were some low-hanging fruits, like we had many inactive databases because we never deleted data belonging to customers that had churned unless requested by the customer. Most of it was free-trial customers. <br>We started working on deleting this data. After deletion and MongoDB server restart, we saw a significant drop in the dhandles count and checkpointing time.</p><p>This was just one part of the solution. How do we make sure that this doesn’t happen again? Since we were creating a dedicated database for every new customer, the dhandles count was unbounded. Hence, we decided to use a common database for all of our new customers. This activity put a hard stop to the ever-increasing dhandles count.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tOuMtG6HMOVfHxXT_MV-TQ.jpeg" /><figcaption>Addressed to dhandles after implementing phase 1</figcaption></figure><p>There were some caveats to the above solution — <br><strong>1. Heterogeneous data model<br></strong>Since we were using a common db for new customers and a dedicated db for old customers, there was no way for the application code to locate data for a customer.</p><pre>Ticket schema - dedicated collection<br>{<br>  id: Number,<br>  title: text<br>}<br><br>Ticket schema - common collection<br>{<br>  id: Number,<br>  body: text,<br>  customer: text<br>}<br></pre><p>For dedicated collections, one can just query with the <strong>ID</strong> filter to get the ticket document, but for common collections, the query must include <strong>customer</strong> and <strong>ID</strong>. Hence, we had to develop another layer to smartly route data requests to the correct database.</p><p><strong>2. Schema migration scripts<br></strong>With new product features, we had to introduce new fields to existing collections. This required running scripts that would update the data for all customers.<br>This activity used to activate dormant dhandles for inactive customers using dedicated collections.<br>We had set a process for reviewing these scripts with a set of SMEs.<br>SMEs could make recommendations to perform the migration for active customers only, or perform migration in batches.</p><h4>Strategize: Reduce dhandles</h4><p>To reduce dhandles, we planned to do the following things —</p><p><strong>Auto customer data deletion job</strong><br>This job would run daily and delete inactive customers’ data from all of our data stores. Since we never moved old customers’ data to common collections, this job would clean dedicated collections and respective dhandles automatically.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*0NfK6EWp371YtAyL4B6GdA.gif" /></figure><p><strong>Data collation<br></strong>We wanted to move data stored in the dedicated collections to common collections. This plan never took off because we decided to move to sharded setup. We will talk about this in our future blogs.</p><h3>More Tuning</h3><p>Apart from the above solution, we additionally did the following things —</p><ol><li><strong>Upgrade MongoDB version from 3.6 to 4.x.xx —</strong> We wanted to use multi-document transaction that was only available from 4.0 onwards.</li><li><strong>Reduce TCP keepalive time from 7200 to 120 seconds — </strong>The default value of TCP keepalive for Linux Systems is too high and can cause connections to be dropped silently.</li></ol><h3>Learnings</h3><p><strong>MongoDB requires restarts — </strong>MongoDB performance keeps deteriorating over time. If you do a restart, things become better suddenly. <br>Even if you delete data, MongoDB doesn’t release resources until an explicit restart is done. In our case, we had to restart the MongoDB setup after bulk deletion.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/1*CObvZ_vCr6-NHex0v_-lvA.jpeg" /></figure><h3>Conclusion</h3><p>Finally, our MongoDB cluster was stable after implementing the above solutions.</p><p>But it’s not the end of the story. One of the recommendations from the MongoDB consultation session was to shard the database after it exceeds 2TB in size. At present, we are migrating large-scale collections to a horizontally scalable database. We will talk about it in our future blogs.</p><p>Stay Tuned!</p><p><em>Thanks to Somya Maithani, </em><a href="https://medium.com/u/8245797404f8"><em>Vineet Naik</em></a><em>, </em><a href="https://medium.com/u/4647487d8947"><em>Rubal Jabbal</em></a><em>, </em><a href="https://medium.com/u/d2c67c866a96"><em>Adityo Deshmukh</em></a><em> and Sameer Patil for the review and suggestions.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8c5d5a2eaf3f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/helpshift-engineering/understanding-and-managing-dhandles-in-mongodb-8c5d5a2eaf3f">Understanding and Managing dhandles in MongoDB</a> was originally published in <a href="https://medium.com/helpshift-engineering">helpshift-engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Thought Experiment: Patching up B-Trees for performance]]></title>
            <link>https://medium.com/@npcoder2k14/thought-experiment-patching-up-b-trees-for-performance-832ed2cdef6e?source=rss-93c26ced7936------2</link>
            <guid isPermaLink="false">https://medium.com/p/832ed2cdef6e</guid>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[b-tree]]></category>
            <dc:creator><![CDATA[Narendra Pal]]></dc:creator>
            <pubDate>Sun, 20 Feb 2022 10:51:58 GMT</pubDate>
            <atom:updated>2023-03-06T08:41:52.555Z</atom:updated>
            <content:encoded><![CDATA[<p>Recently I came upon a limitation with Database Indexes using B-tree(to be specific B+tree).</p><p>Here is the first scenario —</p><p>Consider, Customer Orders sample data with the following schema in a MongoDB database and we have an index on the <strong>created_at</strong><em> </em>field<em>.</em></p><pre>{<br>   &quot;id&quot;         : &lt;String&gt;<br>   &quot;created_at&quot; : &lt;Timestamp&gt;<br>   &quot;updated_at&quot; : &lt;Timestamp&gt;<br>   &quot;status&quot;     : &lt;Integer&gt;<br>   &quot;items&quot;      : &lt;Array of item-ids&gt;<br>}</pre><p>Now, I want to fetch all the orders created on a certain day. I don’t want to burden the database, hence I will paginate this data with <strong>page-size</strong> and <strong>page-number</strong>.</p><p><em>There are other approaches for pagination as well but let’s stick to this approach for the sake of API backward compatibility.</em></p><p>I’ll use the following query to get results from the MongoDB:</p><pre>db.orders.find({&quot;created_at&quot; : {&quot;$gte&quot;: timestamp1<br>                                &quot;$lt&quot; : timestamp2}})<br>         .skip(page-size*page)<br>         .limit(page-size)</pre><p>The above command says —</p><ul><li>Get all the records that have been created between <strong>timestamp1</strong> and <strong>timestamp2</strong>.</li><li>Skip first<em> </em><strong>page-size*page</strong> records.</li><li>Limit the results to <strong>page-size</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1_6vI0CFW1fDtz3cOYHyGw.png" /><figcaption>Image 1: Latency increasing with Skip value</figcaption></figure><p>Now, as the <strong>skip</strong> value starts increasing, the latency starts increasing. It may happen that at the start this query took less than one second and can go up to minutes by the end.</p><h4>We are hitting the index every time so why is the latency increasing?</h4><p>To understand why is this happening let’s dive deep into the Data Structure used here to create the index i.e B+ Tree.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lUQFiSnXxEbtVvAoriabpg.png" /><figcaption>Image 1: B+ Tree</figcaption></figure><blockquote><strong>B+ tree</strong> is an <a href="https://en.wikipedia.org/wiki/M-ary_tree">m-ary tree</a> with a variable but often large number of children per node. Databases store hundreds of keys in a single node. It lets database to find a key with minimum traversal.</blockquote><blockquote>Best thing about B+ Tree is that it can reside in Main Memory and Disk as well. So, if the Index is getting large and can’t fully reside on Main Memory then lower level nodes will be created in disk.<br><strong>source:</strong> <a href="https://en.wikipedia.org/wiki/B%2B_tree">Wikipedia</a></blockquote><p>In the above tree, let’s perform our query. Keep <strong>page-size</strong> as 2 and <strong>page</strong> as 0. We will keep increasing the <strong>page</strong> by 1 for each iteration.</p><pre>+-----------+------+-------+<br>| Iteration | Skip | Limit |<br>+-----------+------+-------+<br>|         1 |    0 |     2 |<br>|         2 |    2 |     2 |<br>|         3 |    4 |     2 |<br>|         4 |    6 |     2 |<br>|         5 |    8 |     2 |<br>+-----------+------+-------+</pre><p>In the last iteration, database fetches 10 records from the index then drops the first 8 records and returns the remaining 2 records.</p><p>In this case, the database has no way of avoiding tree traversal. The database had no use for the first 8 records but still, it ended up fetching them. Now, Imagine these records are stored in the disk then it will be really costly read operation, and for what?</p><p>Another similar scenario — Consider the following Database query:</p><pre>db.orders.find( { &quot;created_at&quot; : {&quot;$gte&quot;: timestamp1<br>                                  &quot;$lt&quot; : timestamp2}})<br>         .count()</pre><p>The above command says —</p><ul><li>Count all the records that have been created between <strong>timestamp1</strong> and <strong>timestamp2</strong>.</li></ul><p>To count all the records within the given time range, the database has to read each and every leaf node matching the condition. In a large dataset, it is highly probable that leaf nodes are residing in the disk. So again it is going to be a costly operation.</p><h3>Modified B+ Tree</h3><p>We have seen two scenarios where the database is unnecessarily reading from the disk.</p><p>In the <strong>B+ Tree, </strong>the internal node has the following structure —</p><pre>+-----+----+-----+----+-----+----+-----+<br>| ref | 11 | ref | 12 | ref | 13 | ref |<br>+-----+----+-----+----+-----+----+-----+</pre><p>The keys are surrounded by references to other nodes. Left reference of key points to a node that has smaller values and right reference points to a node that has equal or larger values.</p><p>To avoid unnecessary reads, I propose the following improvement to the above structure.</p><pre>+-----------+----+-----------+----+-----------+----+-----------+<br>| ref,count | 11 | ref,count | 12 | ref,count | 13 | ref,count |<br>+-----------+----+-----------+----+-----------+----+-----------+</pre><p>You can see that I have added <strong>count </strong>alongside the reference. This count represents the number of keys stored in the reference’s sub-tree.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cHm5pP6LY2etYmLRdqF9aw.png" /><figcaption>Image 2: Modified B+ Tree with the reference count</figcaption></figure><p>You can see the <strong>count</strong> attached to each internal node reference in <em>Image 2</em>.</p><p>Now let’s re-run the two discussed scenarios on this modified structure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bbt_LVbl33iXxqABj_L8sA.png" /><figcaption>Image 3: Skip first 8 records</figcaption></figure><p><strong>In the first scenario</strong>, we want to skip certain records. Taking the same example If I want to skip the first 8 records in the modified structure then —</p><ul><li>Start from the root node i.e. 0017.</li><li>Look at the left reference’s count, it has 6 total keys so we can skip traversing the left subtree altogether. 🎊</li><li>We go to the right subtree node i.e. 0019.</li><li>Again look at the left reference’s count, it has 2 keys so we can skip traversing the left subtree. 🎊</li><li>Now, we have skipped a total of 8 keys so we can pick the remaining 2 keys from the right subtree.</li></ul><p><strong>Comparison</strong>: We have done only 2 reads with <strong>modified B+ Tree</strong> in comparison to 7 reads in the <strong>original B+ Tree</strong>. This is a huge performance improvement for reads.</p><p><strong>In the second scenario</strong>, we want to count records matching certain conditions. If I want to count records less than 0017, then I just need to traverse to the root node’s left subtree and sum all the reference counts.</p><p><strong>Comparison</strong>: We have done 1 read with a <strong>modified B+ Tree</strong> in comparison to 4 reads in the <strong>original B+ Tree</strong>. This is again an amazing performance gain.</p><h3>Maintenance Cost ⛽️</h3><p>We have seen amazing read performance gain for the discussed scenarios but there is a cost for maintaining such a structure. We have to update the reference count every time a node’s size is updated. This will mean all of the parent nodes until the root will be updated as well. Databases generally use a high Degree B+ Tree, hence the depth is nominal. So this shouldn’t be much of a problem.</p><h3>Closing Remarks</h3><p>This is a promising structure with great performance improvement for read-heavy workloads. I didn’t get time to implement and benchmark it. Please share your thoughts on it.</p><p>Cheers!</p><p><em>Thanks to </em><a href="https://medium.com/u/9b8bbe72783c"><em>Vedang Manerikar</em></a><em>, </em><a href="https://medium.com/u/4647487d8947"><em>Rubal Jabbal</em></a><em>, </em><a href="https://medium.com/u/f9572b3d1433"><em>Kiran Kulkarni</em></a><em>, </em><a href="https://medium.com/u/8245797404f8"><em>Vineet Naik</em></a><em> Abhishek gupta, </em><a href="https://medium.com/u/6f5b781ce590"><em>Samuel Chase</em></a><em> and </em><a href="https://medium.com/u/d55fb9904659"><em>Shyam Shinde</em></a><em> for the review and suggestions.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=832ed2cdef6e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>