Understanding MongoDB Sharding Basics
Understanding MongoDB Sharding Basics
Sharding
Unit – 4
Chapter -1
Content:
• Sharding: Introduction to Sharding Understanding the Components
of a Cluster; A One-Minute Test Setup.
1
29-11-2025
How it works
3. Shard Key: A shard key, which can be a field like a user ID or geographic
location, determines which shard a piece of data belongs to.
4. Query Routing: When a query is made, a router directs the request to the
correct shard(s) for processing.
2
29-11-2025
Benefits
3
29-11-2025
4
29-11-2025
• All the complexity of data distribution, request forwarding, and result merging is
handled automatically by the mongos router.
• This design makes it easy to scale MongoDB horizontally — meaning you can
add more machines (shards) to handle more data or users, without changing
how your application connects to the database.
5
29-11-2025
• Imagine you have a database for an online shopping app with 1 crore
(10 million) customer records.
If you store all that data on one server, it will become slow and
overloaded.
So, you split the data into parts and store each part on a different
shard.
In short:
Each shard holds a subset of the total data.
Together, all shards make up the complete database, allowing MongoDB
to handle large-scale data efficiently.
6
29-11-2025
• This opens the shell where you can manually create a cluster setup.
7
29-11-2025
• Now you’re connected to the mongos on port 30999, using the test
database.
8
29-11-2025
Step-by-step Example
1. Start mongosh without connecting to any database:
mongo –nodb
9
29-11-2025
• You’ll see:
• [Link] is sharded.
• Shards like shard0000, shard0001, etc.
• Distribution of chunks across shards.
10
29-11-2025
Shard Configuration
Chap -2
Unit - 4
• Shard servers — these actually hold the data (each shard is a replica
set).
1
29-11-2025
Introduction
• In MongoDB, config servers are essential components of a sharded
cluster, responsible for storing the cluster's metadata.
Config Servers
• Config servers are the brains of your cluster: they hold all of the metadata
about which servers hold what data.
• Set up config server first .
• Make sure that they are running with journaling enabled and that
• Their data is stored on non-ephemeral drives.
(Ensure journaling is turned on, so writes are safely logged on disk. Use
persistent storage, not temporary (ephemeral) drives, so the data is not
lost if the server restarts).
2
29-11-2025
3
29-11-2025
# Config Server 1
mongod --configsvr --replSet configReplSet --port 26050 --dbpath /data/config1 --
bind_ip localhost
# Config Server 2
mongod --configsvr --replSet configReplSet --port 26051 --dbpath /data/config2 --
bind_ip localhost
# Config Server 3
mongod --configsvr --replSet configReplSet --port 26052 --dbpath /data/config3 --
bind_ip localhost
Repeat this on all three config servers. Then, initiate the replica set by
connecting to one of the servers:
mongo --port 27019
Run:
[Link]({
_id: "configReplSet",
configsvr: true,
members: [
{ _id: 0, host: "config1:27019" },
{ _id: 1, host: "config2:27020" },
{ _id: 2, host: "config3:27021" }
]
})
4
29-11-2025
# Shard 1
mongod --shardsvr --replSet shard1 --port 27018 --dbpath /data/shard1 --
bind_ip localhost
# Shard 2
mongod --shardsvr --replSet shard2 --port 27019 --dbpath /data/shard2 --
bind_ip localhost
# Shard 3
mongod --shardsvr --replSet shard3 --port 27020 --dbpath /data/shard3 --
bind_ip localhost
Repeat this on all shard servers. Then, initiate the replica set:
mongo --port 27018
• Run:
[Link]({
_id: "shardReplSet1",
members: [
{ _id: 0, host: "shard1:27018" },
{ _id: 1, host: "shard2:27019" },
{ _id: 2, host: "shard3:27020" }
]
})
5
29-11-2025
6
29-11-2025
7
29-11-2025
8
29-11-2025
Task Description
Add capacity Add new shards (replica sets)
Requirement Each shard must have unique replica set name
Condition No overlapping database names across shards
Command [Link]("replicaSetName/host:port")
9
29-11-2025
Sharding a Collection
• Once sharding is enabled on the database, you can shard a collection
by running the [Link] command and specifying a shard
key.
Example:
[Link]("[Link]", { "name": 1 })
• This command shards the artists collection in the music database
using the "name" field as the shard key.
The { "name": 1 } syntax specifies ascending order for the key.
Index Requirement
• If the collection already exists, there must be an index on the shard
key ("name" in this case).
If the index does not exist, MongoDB will return an error and even
suggest the index to create.
• You can fix it by creating the required index:
[Link]({ "name": 1 })
• Then retry the [Link] command.
• If the collection does not yet exist, MongoDB automatically creates the
shard key index for you.
10
29-11-2025
• What Is a Chunk?
• A chunk is a contiguous range of shard key values.
• Each chunk contains all documents whose shard key values fall within a
specific range, and each chunk resides entirely on one shard.
11
29-11-2025
• Chunk Splitting
• As new documents are inserted, chunks can grow in size.
If a chunk becomes too large, MongoDB will automatically split it
into two smaller chunks to maintain balance.
• For example:
Original chunk: age 3–17
• After splitting:
• Chunk 1: age 3–11
• Chunk 2: age 12–17
• These two chunks together still cover the entire original range (3–17),
but are smaller and easier to distribute across shards.
12
29-11-2025
Concept Description
One chunk per shard Each chunk resides fully on a single shard
Splitting Chunks
• A chunk is a range of shard key values that represents a portion
of data within a collection.
• Each shard holds several chunks.
• MongoDB tries to keep chunk sizes roughly equal to ensure
balanced distribution of data and load.
13
29-11-2025
1. Tracking Inserts
• The mongos (the query router) keeps track of how much data it
inserts into each chunk.
• Each chunk has an internal counter of how many inserts or how
much data has been added.
14
29-11-2025
4. Reset Tracking
• After the split:
• The mongos resets its tracking counters for the original chunk.
• New trackers are created for the newly created chunks.
5. Shard’s Role
• When mongos asks the shard whether a chunk should be split:
• The shard estimates the chunk’s size.
• If it’s too large, it finds split points (based on the shard key values).
• These split points are then sent back to the mongos to carry out the metadata
update.
Note: Chunk splitting doesn’t move data; it just updates metadata on the
config servers. Data movement happens later during the balancing phase,
when the balancer moves chunks between shards to maintain even distribution.
15
29-11-2025
Example
• If the shard key is "age" and documents are:
MongoDB can split between age:13 and age:14, or between age:14 and age:15.
16
29-11-2025
➤ Failure Scenario
• If one or more config servers are down, mongos:
• Cannot complete the split.
• Keeps retrying each time new writes arrive.
• This continuous retrying is called a split storm.
17
29-11-2025
Split Storm
• Cause: Config servers unavailable during chunk split attempts.
• Effect: Repeated failed attempts slow down both the mongos and the
affected shard.
• Prevention:
• Keep all config servers up and healthy.
• If necessary, restart mongos to reset its split counter (to temporarily stop
repeated attempts).
➤ No Global Counter
• MongoDB does not maintain a global chunk size tracker.
• Each mongos process keeps its own local counter of how much data it has written to
each chunk.
➤ Restart Effects
• When a mongos restarts:
• Its counters reset.
• If your deployment frequently spins up and down mongos instances (common in cloud setups),
chunks may never reach the split threshold.
Result:
• Chunks grow larger and larger over time (see Figures 14-5 and 14-6).
•
18
29-11-2025
Method Description
Avoid frequent restarts or dynamic scaling of
Keep mongos stable mongos. Keep them running continuously if
possible.
Configure a smaller chunk size than desired.
Reduce chunk size
Splits will occur earlier (at a lower threshold).
You can disable automatic chunk splitting
entirely by starting mongos with the --nosplit
Use --nosplit option
flag. Useful for testing or very controlled
environments.
19
29-11-2025
• The most important and difficult task when using sharding is choosing
how your data will be distributed.
1
29-11-2025
• Since you included the shard key (userId), MongoDB knows exactly which
shard has this data.
Summery:
• If you have only a few shards (like 3), sending the query to all shards is
not a big deal. But if you have hundreds of shards, it wastes time and
resources.
• Always include the shard key in your queries whenever possible — it
helps MongoDB send your request to the right shard quickly.
2
29-11-2025
• Reduce latency:
You want operations (reads/writes) to be faster — maybe by storing
data on servers closer to users or on faster machines.
• Increase throughput:
You want the system to handle more operations at the same time
(e.g., more reads/writes per second) by distributing work evenly
among shards.
Picking a shard key is like deciding how to divide work among many
workers. if you divide it wisely, everything runs fast and smooth; if you
choose poorly, some workers (shards) will be overloaded while others
sit idle.
3
29-11-2025
• Picturing Distributions
• There are three basic distributions that are the most common ways
people choose to split their data:
• Ascending key,
• Random,
• Location-based.
There are other types of keys that could be used, but most use cases fall
into one of these categories.
4
29-11-2025
• Suppose we create a new document. The answer is the chunk with the
range ObjectId("5112fae0b4a4b396ff9d0ee5") through $maxKey.
• This is called the max chunk, as it is the chunk containing
$maxKey.
5
29-11-2025
6
29-11-2025
7
29-11-2025
8
29-11-2025
• You pick a field in your data to act as the “shard key” (eg. user ID).
• Instead of using the raw value to decide which shard it goes to, you
apply a hash function on that value.
• The resulting hash value is used to map the data to one of the shards.
9
29-11-2025
• Example: You have a collection called users with documents like this:
Steps:
1. Choose Shard Key
• Let’s say we want to shard based on username.
• Instead of using the plain value we’ll use a hashed shard key.
10
29-11-2025
11
29-11-2025
• What is GridFS?
• Instead of storing one big file in a single document, GridFS splits the file into
smaller chunks (default 255 KB each) and stores them across two
collections:
• [Link] → file metadata
• [Link] → actual binary chunks of data
12
29-11-2025
13
29-11-2025
3. Firehose Strategy?
• The Firehose Strategy refers to a data collection approach where all
raw data is captured continuously and stored, even before deciding
what to analyze.
• Instead of selectively collecting only certain data, you collect it all
first, and decide later what’s useful.
Steps:
• you don’t pre-filter what you collect.
• You store all raw logs, sensor readings, user events, clickstreams, etc.
• Later, you process and analyze it for insights.
14
29-11-2025
Example
• Suppose you run an e-commerce website.
• Instead of logging only:
{ "user_id": 123, "item_id": 10, "action": "purchase" }
Summery:
15
29-11-2025
4. Multi-Hotspot:
• A multi-hotspot occurs when multiple keys or ranges in your sharded or
distributed database receive not equally distributed high traffic at the
same time.
• Unlike a single hot shard (where one shard is overloaded), a multi-
hotspot means several shards or key ranges are all “hot” each getting
heavy, uneven load.
Example:
• Imagine a highway with many toll booths (shards).
• If one booth has a huge line - that’s a hot spot.
• If many booths have big lines at once - that’s a multi-hotspot.
Example
Suppose you have a social media app storing posts in MongoDB:
{ "user_id": 101, "post": "..." }
• You shard using user_id as the key:
[Link]("[Link]", { "user_id": 1 })
• Now imagine:
• Users 101, 102, and 103 are celebrities with millions of followers.
• Each gets massive read/write traffic.
• Then:
• Shards holding user_id 101, 102, and 103 become hot simultaneously.
• That’s a multi-hotspot — multiple busy shards, while others are mostly
idle.
16
29-11-2025
Concept Description
Note:
• The first part of the shard key is a random value (to spread writes across
shards).
• The second part is a sequential or ascending value (to keep inserts
efficient within each shard).
17
29-11-2025
Example
• Suppose your shard key is:
{ "region": 1, "timestamp": 1 }
• region = random or low-cardinality value (e.g., North, South, East,
West)
• timestamp = ascending value (insert order)
Then:
• Different regions spread writes across shards
• Timestamps within each region stay in order
• Result:
Even load across the cluster and efficient inserts inside each shard.
18
29-11-2025
If a field has few unique values (like a "logLevel" field with only "DEBUG",
"WARN", or "ERROR"), MongoDB cannot create many chunks.
In such cases, you can use a compound shard key combining a low-
cardinality field with a high-cardinality one (e.g., "logLevel" and
"timestamp") to ensure better data distribution.
19
29-11-2025
Shard Tagging
• You can tag shards and tell
Shard ID Tag Meaning MongoDB to store specific
High-performance collections on shards with certain
shard0000 high
shard tags.
shard0001–
(none) Default shards
0003
shard0004, [Link]("shard0000", "high")
low Low-cost shards
shard0005 [Link]("shard0004", "low")
[Link]("shard0005", "low")
20
29-11-2025
Balancer Migration
• Tag assignment does not move data instantly.
• The balancer gradually moves data to match the new tag
configuration.
• So, existing chunks may take some time to migrate.
21
29-11-2025
Tagging allows you to tell MongoDB which shards should store which collections,
giving you more control over how data is distributed across your cluster.
Assign collection to a tag [Link]("coll", {...}, {...}, "tag") Control where data is stored
Edit manually Use [Link] and [Link] Manage tag data directly
22