MongoDB Horizontal Scaling through Sharding
Tags: mongodb, sharding
Published: 2017-06-13 19:58:42

---
title: MongoDB Horizontal Scaling through Sharding
published: true
description: Sharding in MongoDB
tags: MongoDB, sharding
---
There comes a time in many <a href="https://www.mongodb.com">MongoDB</a> database, or any database for that matter, life cycles in which our data outgrows our servers. Either physically outgrows storage capabilities or the data grows so large that performance is degraded. Even scaling our physical servers up with a more powerful CPU, more RAM, or hard drives (vertical scaling) may not be enough. This is where horizontal scaling through sharding comes into practice.
<h3>Sharding</h3>
What is sharding exactly? It is the practice of distributing data across multiple machines. In MongoDB it supports instances with large data sets and needed high throughput operations. The data is distributed across all shards allowing the workload to be evenly shared. This has the potential for much better efficiency than a single server.

<a href="https://www.kenwalger.com/blog/wp-content/uploads/2017/06/sharding-example.png"><img class="alignnone size-full wp-image-349" src="https://www.kenwalger.com/blog/wp-content/uploads/2017/06/sharding-example.png" alt="Sharded data distribution example" width="600" height="485" /></a>

Each cluster should, for redundancy, also be <a href="https://docs.mongodb.com/manual/replication/">replica sets</a> with <a href="https://docs.mongodb.com/manual/core/replica-set-primary/">primary</a> and <a href="https://docs.mongodb.com/manual/core/replica-set-members/#replica-set-secondary-members">secondary</a> servers.

<a href="https://www.kenwalger.com/blog/wp-content/uploads/2017/06/clusters.png"><img class="alignnone size-full wp-image-350" src="https://www.kenwalger.com/blog/wp-content/uploads/2017/06/clusters.png" alt="Sharded Cluster Example" width="600" height="243" /></a>

MongoDBÂ data is sharded at a <a href="https://docs.mongodb.com/manual/reference/glossary/">collection</a> level, therefore it isn't necessary to distribute the entire database across a sharded environment.
<h3>Cluster Configuration</h3>
There are three components to a <a href="https://docs.mongodb.com/manual/reference/glossary/#term-sharded-cluster">sharded cluster</a> that we need. We need the shards themselves, a query router in the way of a <a href="https://docs.mongodb.com/manual/core/sharded-cluster-query-router/">mongos</a> server, and configuration or <a href="https://docs.mongodb.com/manual/core/sharded-cluster-config-servers/">config servers</a>.

The shards are what store the subset of the data. The config servers store all of the metadata about the cluster and which shard houses what data. Data is stored in <a href="https://docs.mongodb.com/manual/core/sharding-data-partitioning/">chunks</a> on each shard and the config server keeps track of all that information.

The mongos, in its role as a query router, acts as the interface between the application and the data. It routes queries and write operations to the appropriate shards. An application, therefore, will only access the dataÂ <em>through</em> a mongos, never by touching the data itself. Queries are routed via the mongos to all shardsÂ <strong>unless</strong> it can be determined the data resides on a particular shard.

<a href="https://www.kenwalger.com/blog/wp-content/uploads/2017/06/shard-broadcast-operation.png"><img class="alignnone size-full wp-image-351" src="https://www.kenwalger.com/blog/wp-content/uploads/2017/06/shard-broadcast-operation.png" alt="Broadcast Sharding" width="600" height="587" /></a>

There has to be a better way than broadcasting that request toÂ <strong>all</strong> shards though, right? As you might imagine, this "scatter/gather" approach to querying can result in some long running operations. Well, I kind of eluded to it before by qualifying it with the "unless", so there is a better way! Enter the <a href="https://docs.mongodb.com/manual/core/sharding-shard-key/">shard key</a>.
<h3>Shard Keys</h3>
A shard key determines how <a href="https://docs.mongodb.com/manual/core/document/">documents</a> in a collection are distributed across the shards. It is an indexed field, or indexed compound fields, that exists inÂ <strong>every</strong> document in the collection. Recall that MongoDB allows for a <a href="https://docs.mongodb.com/manual/core/data-modeling-introduction/">flexible schema</a>Â within the <a href="https://www.kenwalger.com/blog/nosql/document-model/">document model</a>. This is one consideration when choosing a shard key; every document must have the indexed field.

If provided with a shard key during a query, the mongos knows how to route the request.

<a href="https://www.kenwalger.com/blog/wp-content/uploads/2017/06/shard-targets-operation.png"><img class="alignnone size-full wp-image-352" src="https://www.kenwalger.com/blog/wp-content/uploads/2017/06/shard-targets-operation.png" alt="Targeted shard query" width="600" height="587" /></a>

This can greatly enhance performance. Choosing a good shard key, however, is very important. I'll cover what goes into the selection of a good shard key in a <a href="https://www.kenwalger.com/blog/nosql/choosing-good-shard-key-mongodb/">future post</a>.
<h3></h3>
<h3>Trade offs to Sharding</h3>
As the saying goes, there's no such thing as a free lunch. Sharding is the same way. Sharding your data sets increases infrastructure complexity as well as maintenance. One solution to help mitigate both of these is to utilize a DBaaS such as <a href="https://www.mongodb.com/atlas">Atlas</a>Â to host your MongoDB data.

If queries are run without including a shard key, the "scatter/gather" approach is used. This can result in slow queries, therefore it is definitely something to remember when writing your applications. 

Once a collection is sharded, it cannot be unsharded. Similarly, once a shard key is selected, it cannot be changed. So these steps need to be undertaken with careful planning.

If you are handling things yourself on your own hardwareÂ I have briefly discussed some of the tools which can be used to check performance of a sharded collection in previous posts. Specifically in <a href="https://www.kenwalger.com/blog/nosql/mongodb-cli-tools/">MongoDB CLI Tools</a> and briefly in <a href="https://www.kenwalger.com/blog/nosql/mongodb/mongodb-explain-explained/">MongoDB explain() explained</a>.
<h3>Wrap Up</h3>
When your data has outgrown a single server, sharding is a great approach to keep your database performing well. There are some things to watch out for though. Make sure you choose a good shard key and stay up to date with database maintenance.

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" target="_blank" rel="noopener noreferrer">Amazon Echo</a>Â line of products. Check it out and you can say "Alexa, ask MongoDB what is a Shard?" 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>