MongoDB Shard Cluster Data Distribution
Implement a MongoDB shard cluster to improve data availability and scalability. This setup distributes data across multiple nodes for better performance and resilience as your database needs to expand.
This document will help you successfully deploy Pulse components and configure MongoDB sharding. These steps are designed to ensure a comprehensive setup, enabling efficient data management and scalability for your MongoDB clusters.
MongoDB Shard Cluster Deployment Using accelo
Prerequisites
Before deploying a MongoDB Sharded cluster using Accelo, ensure you meet the following prerequisites:
- Minimum Node Requirement: You can run this setup on a single node.
- MongoDB Version: Ensure you are using MongoDB version 8 for this setup.
- Pulse Integration Version: This setup is designed to work with Pulse version 4.1.x.
Deployment Steps
Deploying Pulse Components on Add-on Nodes
- Set Environment Variables: Set
MONGO_URIto the encrypted URI of thead-dbdatabase on the Pulse core node, enable MongoDB encryption, and setPULSE_SA_NODEtotrue. To generate the encrypted URI, see the Configure Secondary Nodes section in Install Pulse on Multiple Nodes (Docker/Podman-Based).
export MONGO_URI="" # Encrypted URI of the ad-db database on the Pulse core node
export MONGO_ENCRYPTED=true
export PULSE_SA_NODE=true
- Prepare the Installation Directory:
mkdir -p /data01/acceldata/
mv accelo.linux /data01/acceldata/accelo
cd /data01/acceldata/
- Initialize accelo:
./accelo init
source /etc/profile.d/ad.sh
accelo init
accelo info
Setting Up MongoDB Sharding
To set up the MongoDB shard cluster, deploy and initiate the following components in this order:
- Config servers: Deploy the config servers as a replica set on different nodes. Use an odd number of nodes, with a minimum of three.
- Shard servers: Deploy the shard servers as a replica set.
- Query router: Deploy a query router on port 30000 of the main Pulse node, and then initiate sharding by using accelo. Initiating sharding migrates the static files from
ad-dbtoad-sa-router. - Rerouting: Bring down
ad-db_defaulton the main Pulse node, reroutead-sa-routerasad-db, and set the original standalone database asad-db-tmpfor the data migration.
Note
The query router requires an initiated config server replica set, and you can add shards to it only after the shard server replica set is initiated. Deploy the query router after you deploy and initiate both the config servers and the shard servers.
For more information on which networks to use, see Pulse Server Configuration Requirements.
Generate the Configuration Files
Use the sharding_script.py script to generate the configuration files for the config servers, shard servers, and query router. To get the script, contact your Acceldata representative.
- Run the script: Run the following command:
python3 sharding_script.py
- Enter the cluster details: When prompted, enter the number of hosts, the IP address of each host, the number of shards, and the WiredTiger cache size in GB. If you leave the cache size blank, the script uses half of the host memory minus 1 GB. The following example shows the prompts and the generated files for three hosts and five shards:
Enter number of hosts: 3
Enter IP for host 1: 10.100.8.38
Enter IP for host 2: 10.100.8.41
Enter IP for host 3: 10.100.8.44
Enter number of required shards: 5
Enter WIREDTIGER_CACHE_SIZE_GB in GB (default if blank: host_memory/2 - 1): 50
Generated ad-sa-configs.yml_10.100.8.38
Generated ad-sa-shard.yml_10.100.8.38
Generated ad-sa-configs.yml_10.100.8.41
Generated ad-sa-shard.yml_10.100.8.41
Generated ad-sa-configs.yml_10.100.8.44
Generated ad-sa-shard.yml_10.100.8.44
Generated ad-sa-router.yml_10.100.8.38
Generated ad-sa-router_for_migrations.yml_10.100.8.38
- Copy the files to their hosts: Copy each generated file to the host whose IP address appears in the file name. The script generates a config server file and a shard server file for each host, and the query router files for the main Pulse node.
Setting Up the Config Server
Perform the following steps on each host:
- Copy the configuration file: Copy the generated config server file to the add-ons configuration directory:
cp ad-sa-configs.yml_<host IP> $ACCELOHOME/config/docker/addons/ad-sa-configs.yml
- Validate the file: Open the file and verify its content. Set
IS_MONGODB_PRIMARYtotrueon the first host only. - Start the service: Run the following command, and then select CONFIG SERVER DB:
accelo deploy addons
? Select the SA components you would like to install: [Use arrows to move, enter to select, type to filter]
[ ] Kafka Connector
[ ] Kafka 0.10.2 Connector
[ ] StandAlone Connector
[ ] Events
[x] CONFIG SERVER DB
[ ] QUERY ROUTER DB
> [ ] SHARD SERVER DB
- Verify the service status: Run the following command:
docker ps
After you complete these steps on all hosts, log in to the MongoDB shell and verify that all members are part of the replica set:
docker exec -it ad-sa-configs_default bash
mongosh mongodb://admin:<password>@localhost:27017/admin
rs.status()
Setting Up the Shard Server
Perform the following steps on each host:
- Copy the configuration file: Copy the generated shard server file to the add-ons configuration directory:
cp ad-sa-shard.yml_<host IP> $ACCELOHOME/config/docker/addons/ad-sa-shard.yml
- Start the service: Run the following command, and then select SHARD SERVER DB:
accelo deploy addons
? Select the SA components you would like to install: [Use arrows to move, enter to select, type to filter]
[ ] Kafka Connector
[ ] Kafka 0.10.2 Connector
[ ] StandAlone Connector
[ ] Events
[ ] CONFIG SERVER DB
[ ] QUERY ROUTER DB
> [x] SHARD SERVER DB
- Verify the service status: Run the following command:
docker ps
- Change the ownership of the data directories: Run the following commands:
cd $ACCELOHOME/data/
chown 1000:1000 db_sh*
- Restart the service if required: If the shard server service doesn't start the first time, run
accelo deploy addons, clear SHARD SERVER DB, and then select it again.
After you complete these steps on all hosts, log in to the MongoDB shell of a shard server container and verify that all members are part of the replica set. The following example checks the ad-sh1rs1_default container:
docker exec -it ad-sh1rs1_default bash
mongosh mongodb://admin:<password>@localhost:27017/admin
rs.status()
Setting Up the Query Router
Perform the following steps on the main Pulse node:
- Copy the configuration file: Copy the generated query router file to the add-ons configuration directory:
cp ad-sa-router.yml_<host IP> $ACCELOHOME/config/docker/addons/ad-sa-router.yml
- Start the service: Run the following command, and then select QUERY ROUTER DB:
accelo deploy addons
? Select the SA components you would like to install: [Use arrows to move, enter to select, type to filter]
[ ] Kafka Connector
[ ] Kafka 0.10.2 Connector
[ ] StandAlone Connector
[ ] Events
[ ] CONFIG SERVER DB
> [x] QUERY ROUTER DB
[ ] SHARD SERVER DB
- Verify the service status: Run the following command:
docker ps
Initializing Sharding and Migrating Data
Before you initialize sharding, decide the initial number of shards and zones based on your data retention requirements. Keep the following in mind:
- Define the zone size in days, not in weeks or months. For example, four zones of 7 days each hold 28 days of data, not a month.
- If you specify x zones, accelo creates x + 1 zones. The additional zone is a buffer.
To initialize sharding and migrate the data, perform the following steps:
- Initialize database sharding: On the main Pulse node, where both
ad-dbandad-sa-routerare running, run the following command and respond to the prompts. Run this command for every cluster in Pulse.
accelo admin database init-sharding-db
INFO: Initiating database sharding
Is the 'Database Service' up and running? [y/n]: : y
Is ad-db service acting as query router? [y/n]: n
WARN: Gauntlet is running in dry run mode. Disable this to delete indices from elastic and purge data from mongo DB
Enabling sharding for cluster odp_odin
✔ Enter initial shards count: : 5
✔ Do you want to migrate static configuration collections from standalone database(ad-db) ? [y/n]: : y
- Verify the sharding status: Run the following commands:
docker exec -it ad-sa-router_default bash
mongosh mongodb://admin:<password>@localhost:27017/admin
sh.status()
- Convert ad-db to a router: In the
/data01/acceldata/config/docker/ad-core.ymlfile, add the environment variables and extra hosts from the generatedad-sa-router.ymlfile to the ad-db service, and update the data volume as shown in the following example:
version: "2"
services:
ad-db:
image: ad-database
container_name: ""
environment: # Add the environment variables from ad-sa-router.yml
volumes:
- /data01/acceldata/config/db/mongokey:/mongokey
- /etc/localtime:/etc/localtime:ro
- /data01/acceldata/data/db_router:/data/db # Update this volume
ulimits: {}
ports:
- 27017:27017
depends_on: []
opts:
memory: "53687091200"
restart: ""
extra_hosts: # Add the extra hosts from ad-sa-router.yml
-
network_alias: []
ad-deployer:
- Restart ad-db: Run the following command:
accelo restart ad-db -d
- Deploy the query router for migration: Copy the generated migration file over the query router configuration file:
cp ad-sa-router_for_migrations.yml_<host IP> $ACCELOHOME/config/docker/addons/ad-sa-router.yml
Then, run the following command and select QUERY ROUTER DB:
accelo deploy addons
? Select the SA components you would like to install: [Use arrows to move, enter to select, type to filter]
[ ] Kafka Connector
[ ] Kafka 0.10.2 Connector
[ ] StandAlone Connector
[ ] Events
[ ] CONFIG SERVER DB
> [x] QUERY ROUTER DB
[ ] SHARD SERVER DB
- Verify the service status: Run the following command:
docker ps
- Verify the rerouting and create the indices: Verify that
ad-dbnow works as a router and thatad-db-tmpcontains the old data. Then, create the indices and reload the events for all clusters:
docker exec -it ad-db_default bash
mongosh mongodb://admin:<password>@localhost:27017/admin
sh.status()
docker exec -it ad-db-tmp_default bash
mongosh mongodb://admin:<password>@localhost:27017/admin
show dbs
# The output must include the old data.
# Run the following commands for all clusters.
accelo admin database index-db
accelo admin database reload-events
- Migrate the data: Migrate the data from ad-db-tmp_default to ad-sa-router_default. Exclude the acceldata database and the static configuration collections, because they were migrated when you initialized sharding. First, create a dump of the data:
docker exec -it ad-sa-router_default bash
cd /data/db
nohup mongodump -h <ad-db-tmp IP>:<ad-db-tmp port> -u accel -p <password> --authenticationDatabase admin &
Wait for the dump to complete. If you initialized sharding for all clusters, remove the static data from the dump:
rm -rf ./dump/acceldata
rm -rf ./dump/*/cluster_info.bson
rm -rf ./dump/*/cluster_info.metadata.json
rm -rf ./dump/*/configurations.bson
rm -rf ./dump/*/configurations.metadata.json
rm -rf ./dump/*/inventory.bson
rm -rf ./dump/*/inventory.metadata.json
Stop the balancer, restore the data, and monitor the restore:
# Stop the balancer
sh.stopBalancer()
# Restore the data
nohup mongorestore -h localhost:27017 -u accel -p <password> --authenticationDatabase admin ./dump &
# Check the restore status
ps -ef | grep mongorestore
tail -f nohup.out
After the restore completes, validate the data by comparing the document counts in ad-db-tmp and ad-sa-router:
Save the following validation script as count_all_documents.js on the main Pulse node. The script counts the documents in every collection of every database, except the admin, local, and config system databases.
// count_all_documents.js
//
// Counts documents in every collection, across every database, on a
// MongoDB deployment (standalone, replica set, or sharded cluster via mongos).
//
(function () {
// System databases to skip by default. Set to [] to include them too.
var EXCLUDE_DBS = ["admin", "local", "config"];
var dbList = db.adminCommand({ listDatabases: 1 }).databases;
var grandTotal = 0;
dbList.forEach(function (dbInfo) {
var dbName = dbInfo.name;
if (EXCLUDE_DBS.indexOf(dbName) !== -1) {
return;
}
var currentDb = db.getSiblingDB(dbName);
var collections = currentDb.getCollectionNames();
var dbTotal = 0;
collections.forEach(function (collName) {
// Skip internal system collections (system.indexes, system.views, etc.)
if (collName.indexOf("system.") === 0) {
return;
}
var count = currentDb.getCollection(collName).countDocuments({});
dbTotal += count;
print(" " + dbName + "." + collName + ": " + count);
});
grandTotal += dbTotal;
print(dbName + " total: " + dbTotal);
print("----------------------------------------");
});
print("========================================");
print("GRAND TOTAL DOCUMENTS (all dbs, all collections): " + grandTotal);
print("========================================");
})();
Run the script against both databases. Replace <password> with the MongoDB admin password.
docker exec -i ad-db-tmp_default mongosh "mongodb://admin:<password>@localhost:27017/admin" --quiet < count_all_documents.js
docker exec -i ad-sa-router_default mongosh "mongodb://admin:<password>@localhost:27017/admin" --quiet < count_all_documents.js
Compare the count for each collection and the GRAND TOTAL DOCUMENTS value in both outputs. The counts must match.
After you validate the data, start the balancer:
sh.startBalancer()
- Verify the migrated data: Run the following commands:
docker exec -it ad-db_default bash
mongosh mongodb://admin:<password>@localhost:27017/admin
show dbs
- Remove the query router service: After the migration completes, run the following command and clear QUERY ROUTER DB:
accelo deploy addons
? Select the SA components you would like to install: [Use arrows to move, enter to select, type to filter]
[ ] Kafka Connector
[ ] Kafka 0.10.2 Connector
[ ] StandAlone Connector
[ ] Events
[ ] CONFIG SERVER DB
> [ ] QUERY ROUTER DB
[ ] SHARD SERVER DB
- Push the configuration: Run the following command:
accelo admin database push-config
Adding New Shards in the Future
Purpose:
- To extend data retention capabilities.
- To enhance the performance of the existing cluster.
Procedure:
- Add the shard to the shard server configuration: Add a new shard entry in the
ad-sa-shard.ymlfile. - Add the shard to ad-db: Run the following command in the MongoDB shell of ad-db:
sh.addShard("shardXrs/IP:HOST")
Final Steps
Ensure you've correctly set up and configured each part of your MongoDB sharding environment. Regularly check the status of your sharding setup and make adjustments as needed to maintain optimal performance and data management.

Have a suggestion?