Data Durability in MongoDB
Tags: mongodb, writeconcern, readconcern
Published: 2017-08-25 00:32:15

---
title: Data Durability in MongoDB
published: true
description: Making sure we have data durability in our applications is an important aspect of any application design. Let's take a look at how we can do so in MongoDB.
tags: MongoDB, write concern, read concern
cover_image: https://thepracticaldev.s3.amazonaws.com/i/3ot2yxzlwkpwdmefxitv.png
canonical_url: https://www.kenwalger.com/blog/nosql/mongodb/data-durability-mongodb/
---

When designing a database we want to make sure the data that we want to be stored actually <strong>gets</strong> stored. Data durability is a key factor in applications. Â On local servers and test environments, this typically isn't a huge issue. We can pretty easily tell when and if our environment crashes. What happens though as our system grows? What happens when we move to a distributed environment with many different pieces to our application puzzle?

In addition to many of the <a href="https://www.kenwalger.com/blog/nosql/mongodb/mongodb-performance-issues/">performance</a> considerations that <a href="https://www.mongodb.com">MongoDB</a> has improved upon in recent versions, data durability is another improvement. It is also a topic from previous versions for which the product took some heat. Let's take a look at some ways which we can design our applications around the idea of data durability.
<h3>Data Durability</h3>
There are a couple of different scenarios we need to consider when dealing with data durability, reads and writes. Let's take a look at these two different considerations. In doing so we'll see some ways to ensure our system is doing what we intend it to be doing.
<h4>Writes</h4>
Write operations in MongoDB follow a pretty clear path in MongoDB. At least in theory. From an application, they get sent to the <a href="https://docs.mongodb.com/manual/reference/glossary/#term-primary">primary</a> server, in a <a href="https://docs.mongodb.com/manual/reference/glossary/#term-replica-set">replica set</a> situation. The data goes into an in-memory store and <a href="https://docs.mongodb.com/manual/reference/glossary/#term-oplog">oplog</a>. At this point, the server, by default, sends back an "okey dokey" to the application.

Notice that I haven't mentioned anything about writing data to disk yet. It hasn't happened yet. The primary then writes the data to the <a href="https://www.kenwalger.com/blog/nosql/mongodb/mongodb-storage-engine-journaling/">journal</a> file and then to disk. The secondaries are writing data to the disk during this process as well, at some point after the data has been written to the journal.

This can be all well and good in many situations as we are talking about small time frames between the application getting an "okay" and the data being persisted to disk. But there is still some latency there. Should something go wrong with the distributed system during that time, extra steps have to be taken to get the data. The application thinks is there, it did get a confirmation of it after all, and what actually took place with the disk writes.

I'm not going to go into the background of whatÂ <em>actually</em> goes on behind the scenes during an unexpected shutdown or failure. It is a bit beyond the scope of this particular post. I will show how to instruct MongoDB to wait to send our "okey dokey" signal to the application until the data is indeed on disk.
<h6>Write Acknowledgment</h6>
MongoDB has provided the functionality to set a level of acknowledgment for write operations with the <a href="https://docs.mongodb.com/manual/reference/write-concern/">write concern</a> options. There are a few different options available for us here.
<ul>
 	<li>We can request an acknowledgment that data has been written to a specific number of servers in a replica set with the <code>w</code> option.</li>
 	<li>TheÂ <code>j</code> option requests acknowledgment of the data being written to the journal. This is a boolean value.</li>
 	<li>There is also a <code>wtimeout</code> optionÂ which, as the name might lead you to deduce, sets a timeout, in milliseconds, for the acknowledgment to occur.</li>
</ul>
With the <code>w</code> option, we can choose to tell MongoDB a specific number of servers that must confirm the write operation. Or, there is a handy "majority" option that allows for the write acknowledgment to occur when a majority of the data bearing members of the replia set have performed the write.

If, for example, we want to insert a document in the <a href="https://docs.mongodb.com/getting-started/shell/client/">mongo shell</a> and wait for a response from two members of our replica set with a two and a half second timeout period, we could do the following:
<pre><span class="nx">db</span><span class="p">.</span><span class="nx">blogs</span><span class="p">.</span><span class="nx">insert</span><span class="p">(</span>
   <span class="p">{</span> <span class="nx">title</span><span class="o">:</span> <span class="s2">"Data Durability in MongoDB"</span><span class="p">,</span> <span class="nx">length</span><span class="o">:</span> <span class="mi">1099</span><span class="p">,</span> <span class="nx">topic</span><span class="o">:</span> <span class="s2">"MongoDB"</span> <span class="p">},</span>
   <span class="p">{</span> <span class="nx">writeConcern</span><span class="o">:</span> <span class="p">{</span> <span class="nx">w</span><span class="o">:</span> <span class="mi">2</span><span class="p">,</span> <span class="nx">wtimeout</span><span class="o">:</span> <span class="mi">2500</span> <span class="p">}</span> <span class="p">}</span>
<span class="p">)</span></pre>
<h6>Uses</h6>
So why not just always set a write concern? The main reason is latency. The more servers that must respond with an "okay", the longer it will take for the application to get that response. In a distributed environment, the physical servers may be located all over a given country, or around the world. It is a trade off between responsiveness for the application and data durability.

A good compromise, however, for application performance and data durability is to set w: 2 for your write concern. For writes thatÂ <strong>must</strong> be acknowledged, however, choose <code>w: "majority"</code>.
<h4>Reads</h4>
What about reading our data and making sure that our application has the most recent data? How can we prevent dirty reads, reads that occur during the time frame between the in-memory storage of the data and the actual writing of the data to disk? Reads that might be affected by <a href="https://docs.mongodb.com/manual/core/replica-set-rollbacks/">rollback</a> with a failure occurring?

Similar to write concern, MongoDB offers, as of version 3.2, aÂ <em>read concern</em>. Based on our knowledge of write concern, we can extrapolate that <a href="https://docs.mongodb.com/manual/reference/read-concern/index.html">read concern</a> allows us to specifyÂ which data to return from a replica set. There are three options we can choose when selecting a read concern level.
<ul>
 	<li><code>local</code> - this default setting returns the most recent data with no guarantee that the data will be impacted by a rollback.</li>
 	<li><code>majority</code> - returns data that has been written to a majority of the data bearing members of the replica set.</li>
 	<li><code>linearizable</code> - returns data that reflects all successful writes issued with a write concern ofÂ "majority" <em>and</em>Â acknowledged prior to the start of the read operation. Linearizable was introduced in <a href="https://www.kenwalger.com/blog/nosql/new-version-new-features/">version 3.4</a> and is another great feature of that release.</li>
</ul>
Dirty reads may seem like a huge concern. In practice, however, we want to design our application to properly handle the write operations so that we can negate these concerns. There are times, though, such as reading passwords, that making sure we are reading the most recent and durable data is critical.
<h3>Wrap Up</h3>
MongoDB continues to listen to the community and address the concerns (no pun intended) of their users. The data durability issues of old shouldn't be a reason to not give MongoDB a try.

There is also a great talk from <a href="https://explore.mongodb.com/?page=0&amp;prevItm=349629841&amp;prevCol=648867&amp;ts=71115539">MongoDB World 2017</a> by <a href="https://www.linkedin.com/in/adkomyagin">Alex Komyagin</a> onÂ <em><a href="https://explore.mongodb.com/vidyard-all-players/mongodb-world-presentations-regency-c-alex-komyagin-6-21-2017">ReadConcern and WriteConcern</a></em>. I would recommend having a look at that talk for additional information and use cases.

<hr />

There are several MongoDB specific terms in this post. I created a <a href="https://www.echoskillstore.com/MongoDB-Dictionary/45103">MongoDB Dictionary</a> skill for the <a href="https://www.amazon.com/gp/product/B01DFKC2SO/ref=as_li_tl?ie=UTF8&amp;camp=1789&amp;creative=9325&amp;creativeASIN=B01DFKC2SO&amp;linkCode=as2&amp;tag=kenwalgersite-20&amp;linkId=f9e513223de2525a72b95cf9561db55b" rel="noopener noreferrer">Amazon Echo</a>Â line of products. Check it out and you can say "Alexa, ask MongoDB what is a document?" and get a helpful response.

<hr />

<em>Follow me on Twitter <a href="https://www.twitter.com/kenwalger">@kenwalger</a> to get the latest updates on my postings, or see the original post on my <a href="https://www.kenwalger.com/blog" target="_blank">blog</a>.</em>