Skip to content

MongoDB sharding in depth: config servers, chunks, and balancer behaviour

Keep a sharded MongoDB cluster healthy in production by choosing a sound shard key, checking how data is spread across shards, and controlling when the balancer moves it. You will also be able to spot and fix jumbo chunks and orphaned documents.

This article is for people who run a sharded MongoDB cluster, or are about to, and need to keep it healthy day to day. Sharding splits a large collection across several servers, called shards, so no single machine holds all the data. Each shard is a replica set, meaning a small group of servers that keep copies of the same data. Config servers store the map of which data lives where. A router process called mongos sits in front of everything and sends each query to the right shard. The part that decides whether all this works is the shard key, the indexed field MongoDB uses to assign each document to a shard. A well-chosen key spreads reads and writes evenly as the cluster grows. A poor one sends every new write to the same server and keeps the balancer, the background job that moves data between shards, busy for months. The sections below show how to check the spread of chunks, which are slices of the key range of about 128 MiB each by default. They also cover setting up each tier and avoiding the traps that hurt most in production.

How to verify

From any mongos, inspect the topology and current chunk distribution:

mongosh --host mongos.example.internal:27017
sh.status({ verbose: true })
db.adminCommand({ listShards: 1 })
use config
db.chunks.aggregate([{ $group: { _id: "$shard", n: { $sum: 1 } } }])
db.collections.find({}, { _id: 1, key: 1, balancing: 1 }).pretty()

The first command should list every shard, the config-server replica-set, and per-database primary shards. The chunks aggregation reveals the actual chunk count per shard — a balanced cluster has values within ~8 chunks of each other (the default balancer threshold).

What’s happening

A sharded collection is partitioned by a shard key — one or more indexed fields chosen at shardCollection time. The cluster splits the key range into chunks (default ~128 MiB) and assigns each chunk to a shard. The balancer runs on the elected config-server primary, scanning the chunk distribution every few seconds; when one shard exceeds the migration threshold relative to another, it schedules a chunk move. A move is a multi-step protocol: clone the documents to the receiver, replicate the writes that arrived during the clone, then commit the metadata change atomically via the config servers.

mongos is stateless. It caches the routing table (which chunks live on which shard) and refreshes it on stale-config errors. Every query path — find, update, aggregate, change stream — first asks “does the query include the shard key?” If yes, the query is targeted to one shard. If no, it becomes a scatter-gather broadcast to every shard and merged in the router. A workload that mostly scatter-gathers is a workload that does not scale with shards added.

The shard key choice is the single most consequential design decision. A monotonically increasing key (timestamp, ObjectId in time-order) sends every new write to the last chunk on the last shard — a hot spot. A high-cardinality, well-distributed key (hashed _id, a tenant ID combined with something selective) spreads writes evenly. Hashed sharding ({ field: "hashed" }) trades range-query efficiency for guaranteed write distribution.

The procedure

  1. Stand up config servers as a 3-node replica-set. The config tier holds metadata only — small but critical. Run on dedicated nodes with the --configsvr flag and replSetName: configReplSet.

    sharding:
      clusterRole: configsvr
    replication:
      replSetName: configReplSet
    net:
      bindIp: 0.0.0.0
      port: 27019
  2. Each shard is its own replica-set. Initiate with --shardsvr on every member. A production minimum is 3 nodes per shard — anything less surrenders the durability story.

  3. Start mongos routers in front of the cluster. They have no on-disk state; run two or more behind a load balancer for HA. Point them at the config replica-set:

    sharding:
      configDB: configReplSet/cfg1:27019,cfg2:27019,cfg3:27019
  4. Enable sharding per database, then per collection. Pick the shard key based on the dominant query pattern, not on what feels natural.

    sh.enableSharding("orders")
    db.orders.createIndex({ tenantId: 1, _id: 1 })
    sh.shardCollection("orders.invoices", { tenantId: 1, _id: 1 })
  5. Pre-split for known load. If you know you will load 500 GB at go-live and the key is hashed, pre-split into chunks before the data lands. The balancer is slow compared to a bulk insert hot spot.

    sh.shardCollection("events.raw", { _id: "hashed" }, false, { numInitialChunks: 256 })
  6. Set a balancer window. Move work to off-peak when possible — chunk migrations consume IO on both sides.

    use config
    db.settings.update(
      { _id: "balancer" },
      { $set: { activeWindow: { start: "01:00", stop: "05:00" } } },
      { upsert: true })

Common pitfalls

  • Jumbo chunks — a chunk whose key range hosts more data than the configured chunksize and cannot be split (because every document has the same shard-key value). Jumbo chunks are not movable; resolve by re-sharding with a more selective key.
  • Orphan documents — leftover docs on the donor shard after a migration fail. cleanupOrphaned (or auto-cleanup, which has been default since 4.4) removes them; ignoring them inflates counts and skews aggregations.
  • Targeted queries that aren’t — if the query plan does not include the shard key, mongos scatter-gathers. Always check with explain("executionStats") and look for shards in the output.
  • Re-sharding under load — the online reshardCollection (5.0+) is a heavy operation that doubles storage usage during the cut-over. Plan for it, do not improvise it.
  • Config-server outage — losing the config replica-set primary blocks chunk migrations and split decisions but reads/writes against existing chunks continue. Restore quorum before issuing DDL.

Stack Harbor operates sharded MongoDB clusters for clients whose workloads grew past what a single replica-set could absorb. We design the shard key against the real query mix, pre-split to avoid the cold-start hot spot, and run chunk-distribution dashboards that alert before the balancer starts thrashing. See /en/solutions/clustered-environments/ for the engagement model we use with teams running multi-shard MongoDB in production.