Choosing a good Shard Key in MongoDB
Tags: mongodb, sharding, nosql, shardkey
Published: 2017-06-12 14:26:24

---
title: Choosing a good Shard Key in MongoDB
published: true
description: Choosing a good Shard Key in MongoDB
tags: MongoDB, sharding, NoSQL, Shard Key
cover_image: https://thepracticaldev.s3.amazonaws.com/i/1g7twc8ksit03sihaw0f.png
---

I discussed, at a high level, the concept of sharing in <a href="https://www.mongodb.com">MongoDB</a> in a <a href="https://www.kenwalger.com/blog/nosql/mongodb-horizontal-scaling-sharding/">previous post</a>. I mentioned that I would talk about what makes for a good shard key later on, and here we are. Before we talk about how to choose a good shard key, let's first discuss it's purpose.
<h3>When do we need to shard?</h3>
There are three typical reasons that we will want to shard a collection.
<ol>
 	<li>The write workload on a single server exceeds that server's capacity.</li>
 	<li>The working set no longer fits into RAM.</li>
 	<li>A single server can no longer handle the size of the dataset.</li>
</ol>
However, sharding earlier is better in an application's lifecycle. There are significant performance considerations when sharding an existing collection.
<h3>Why do we need a Shard Key?</h3>
The shard key determines how data, specifically a collection's <a href="https://docs.mongodb.com/manual/reference/glossary/#term-document">documents</a>, will be distributed across a <a href="https://docs.mongodb.com/manual/reference/glossary/#term-shard">sharded cluster</a> in MongoDB. In a sharded collection, MongoDB uses the shard key to partition the data based on ranges of the key. Each range of the shard key values defines a non-overlapping value range. Further, each range is assigned to a specific <a href="https://docs.mongodb.com/manual/reference/glossary/#term-chunk">chunk</a> on the cluster. Sharded environments generally evenly distribute the chunks.

<a href="https://www.kenwalger.com/blog/wp-content/uploads/2017/06/ShardingExample.png"><img class="alignnone size-full wp-image-363" src="https://www.kenwalger.com/blog/wp-content/uploads/2017/06/ShardingExample.png" alt="Sharding Example with Shard Key" width="600" height="366" /></a>

The query router (the <a href="https://docs.mongodb.com/manual/reference/program/mongos/">mongos</a> server) directs the query to the appropriate chunk as data is requested from an application. It does the same for write requests, based on the shard key it directs to write to the appropriate chunk.
<h3>Choosing a Shard Key</h3>
As with MongoDB <a href="https://www.kenwalger.com/blog/nosql/document-model/">schema design</a> considerations, choosing a shard key is heavily dependent on your application. The most frequent information needed to be read from and/or written to the database should be a key contributing factor. Depending on the application perhaps using a hashed ObjectId would be enough. In other applications, a single field may not be enough and a compound sharding key will be necessary.

When choosing a shard key, it impacts the cluster balancer and distribution of data across the shards. This has a large impact on sharded cluster performance and efficiency. An ideal shard key will allow for an even distribution of documents throughout the entire cluster. Beyond application specific requirements, there are a couple of technical factors to consider when choosing a shard key. A shard key cannot be changed once chosen for a collection,Â so these considerations are important.
<h4>Technical Considerations</h4>
The first consideration is <a href="https://docs.mongodb.com/manual/reference/glossary/#term-cardinality">cardinality</a>. A shard key with high cardinality allows for better horizontal scaling. It does not, however, guarantee even data distribution across a sharded cluster.

TheÂ frequency of data is another factor in a good shard key. If the indexed field is, say user_name, and the data set is on the <a href="https://www.amazon.com/gp/product/1460903404/ref=as_li_tl?ie=UTF8&amp;camp=1789&amp;creative=9325&amp;creativeASIN=1460903404&amp;linkCode=as2&amp;tag=kenwalgersite-20&amp;linkId=9383b6bb9334665f74c500b0b5805df8" rel="noopener noreferrer">genealogical data for the Alger</a><img src="//ir-na.amazon-adsystem.com/e/ir?t=kenwalgersite-20&amp;l=am2&amp;o=1&amp;a=1460903404" alt="" width="1" height="1" border="0" /> family, it would be expected that "Alger" occurs much more frequently than other names. This would cause the balance of documents to be uneven across the shards. One wants to choose a key that has low frequency, but that itself won't guarantee even data distribution either.

High cardinality and low frequency are indeed important factors in shard key selection. The rate of change is the third leg of the shard key selection stool. Selecting a key that does not increase, or decrease, monotonically is important as well. A key that isÂ <em>always</em> increasing results in inserts being routed to the shard with the <code>maxKey</code>Â as the upper bound. Thus, the shard will become unbalanced. With the <code>minKey</code>Â as the lower bound, decreasing results will be routed to that shard.

Each of these three legs of our stool contributes to data distribution. We need to consider each factor when selecting a key.
<h3>Example Shard Keys</h3>
Now that we have seen what some of the factors play into sharding performance, let's look at some examples. To borrow a Hollywood movie title,Â <a href="https://www.amazon.com/gp/product/6301971272/ref=as_li_tl?ie=UTF8&amp;camp=1789&amp;creative=9325&amp;creativeASIN=6301971272&amp;linkCode=as2&amp;tag=kenwalgersite-20&amp;linkId=fa8bf8fb3c4c453fc62b81d763c7e41a" rel="noopener">The Good, the Bad &amp; the Ugly</a><img style="border: none !important; margin: 0px !important;" src="//ir-na.amazon-adsystem.com/e/ir?t=kenwalgersite-20&amp;l=am2&amp;o=1&amp;a=6301971272" alt="" width="1" height="1" border="0" />, this can be true of our keys as well.

Shard keys must be based off an indexed field in the collection which exists across all documents. They can also be generated on a <a href="https://docs.mongodb.com/manual/reference/glossary/#term-compound-index">compound index</a> in which the shard key is a <a href="https://docs.mongodb.com/manual/core/index-compound/#compound-index-prefix">prefix</a> of that index. I covered indexing in MongoDB <a href="https://www.kenwalger.com/blog/nosql/mongodb/indexing-in-mongodb/">previously</a>, as it is a topic all of itself. Since there are things to think about when indexing, it also impacts the shard keys.
<h5>The Ugly</h5>
I would say thatÂ <em>ugly</em> shard keys are those that not only don'tÂ <em>help</em> your application but actually result in worse performance than when starting out. This would be something akin to using the <code>_id</code> field without <a href="https://docs.mongodb.com/manual/core/hashed-sharding/">hashing</a>. SinceÂ <code>_id</code>Â is monotonically increasing, it would lead to an unbalanced system.
<h5>The Bad</h5>
I would categorize shard keys as bad that don't fully take advantage of the concept of sharding. If, for example, collections are distributed across the shards and chunks, but the application's read requests typically use an index different from the shard key index.Â While they may not have a negative impact on physical data distribution, they just aren't properly optimized.

This results in a scatter/gather approach to the queries. The mongos server will scatter the request to all shards. Then gather the results together to send to the application. A targeted single server should be receiving the query with a well-chosen key.
<h5>The Good</h5>
This is where we all want to live, right? In a highly performant system environment with everything highly scaled and efficient. This can be achieved by selecting a shard key for a collection which optimizes an application's needs with the technical strategies listed above.
<h3>Wrap Up</h3>
Choosing a correct shard key and the development of a sharding strategy is not always easy. Don't make the mistake that because one application is sharded in a particular way, with a particular shard key, that it is a universal approach. Your application's strategy may be entirely different, or sharding may not be the right solution for a particular collection.

Remember thought, that it is important to establish a shard key and split your data early on. Sharding becomes more challenging in production with large data sets.

There are a lot of 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 Shard Key?" 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.</em>