Skip to content
LESSON 48 / 50Advanceddistributed

Sharding Architecture: mongos, Config Servers & Shards

MongoDB horizontally partitions massive collections across multiple independent physical clusters (Shards) coordinated by query routers (mongos) and metadata catalogs (Config Servers).

Interactive Engine Simulator

Horizontal Sharding, mongos Router & Chunk Balancer

Observe mongos single-shard routing vs scatter-gather queries and automatic chunk migration across replica sets.

mongos Query Router

Stateless routing daemon. Caches routing table from Config DB. Clients connect directly to mongos on port 27017.

Config Replica Set (CSRS)

Stores cluster catalog, database mappings, and chunk range boundaries in config.chunks with two-phase commit lock.

Chunk Balancer

Background round-robin process. Triggers migration when chunk difference between shards exceeds the migration threshold.

Shard 01 (Replica Set: rs-shard-01)3 Chunks
chunk-1Range: [MinKey .. 1000)
450 docs
chunk-2Range: [1000 .. 2000)
820 docs
chunk-3Range: [2000 .. 3000)
610 docs
Shard 02 (Replica Set: rs-shard-02)1 Chunks
chunk-4Range: [3000 .. MaxKey)
390 docs
MONGOS_LOG:Cluster balanced across 2 shards. Shard key: { user_id: 1 }.

1. Formal Definition & Architecture Intent

MongoDB Sharding is a distributed horizontal scale-out architecture that partitions data across multiple independent replica sets (Shards). It consists of three core components: 1. Shards (replica sets holding partitions of data), 2. Config Database (3-node replica set storing cluster routing metadata), and 3. mongos (stateless query routers that route client requests).

2. Explain Like I'm 5 (Mental Model)

Think of an international postal system: Shards are the regional delivery warehouses in different cities. The Config Server is the central postal map listing which zip codes belong to which city. mongos routers are the postal sorting clerks who read the envelope address and send the letter straight to the right warehouse.

3. Real-World Architecture Example

A 50TB multi-tenant SaaS application partitioned across 4 shards.

Sample BSON Documents:
Collection: db.shards_manifest
{
  "shards": [
    {
      "_id": "shard01",
      "host": "rs-shard01/node1:27018,node2:27018"
    },
    {
      "_id": "shard02",
      "host": "rs-shard02/node3:27018,node4:27018"
    }
  ],
  "configsvr": "rs-config/cfg1:27019,cfg2:27019,cfg3:27019",
  "mongos": "stateless router on port 27017"
}

Clients connect exclusively to mongos routers; the sharding architecture is completely transparent to the application.

4. MQL Implementation Steps

Step 1: Check sharding cluster status in mongos
sh.status();
Displays shards, databases, chunk counts, and balancer status.
Step 2: Enable sharding on a database and shard a collection
sh.enableSharding("enterprise_app");
sh.shardCollection("enterprise_app.users", { "tenant_id": "hashed" });
Uses hashed sharding on tenant_id for even chunk distribution.

5. Critical Engineering Rules

Rule / ConstraintUnderlying Reason & Impact
mongos (Stateless Router)Applications connect to mongos. It caches routing metadata from config servers and routes queries.
Config Server Replica SetMandatory 3-node replica set; stores chunk mappings and routing tables. Uses Raft consensus.
Targeted vs Scatter-GatherQueries containing the shard key route directly to 1 shard; queries missing the shard key must broadcast to ALL shards.

6. Deep Dive: Targeted Query Routing vs Scatter-Gather Broadcast

The golden rule of sharding is Query Routing Efficiency. If a query filters on the shard key: db.orders.find({ tenant_id: 42 }), mongos consults its in-memory chunk map and sends the query directly to Shard 2 (Targeted Query). If the query omits the shard key: db.orders.find({ email: "user@test.com" }), mongos must broadcast the query to EVERY shard in the cluster (Scatter-Gather), wait for all responses, and merge them, bottlenecking cluster throughput.

// Check if query was targeted or scatter-gather:
db.orders.find({ email: "a@b.com" }).explain().queryPlanner.winningPlan;
// Stage: "SHARD_MERGE" indicates a scatter-gather broadcast!
Production Warning: A cluster dominated by scatter-gather queries will suffer degraded throughput as shards increase.

7. Architectural Trade-offs

Advantages
  • •Horizontal scale-out: scales write throughput, read throughput, and RAM beyond a single machine's limits
  • •Sharding is completely transparent to application code via the mongos router interface
  • •Automated chunk balancing migrates data across shards in the background
Disadvantages & Gotchas
  • •Operational complexity: requires managing config replica sets, mongos routers, and multiple shard clusters
  • •Scatter-gather queries missing the shard key suffer latency penalties across shards

8. Technical Interview Questions

Q1: What is the role of the Config Server replica set in a MongoDB sharded cluster?

The Config Server replica set stores the cluster's authoritative metadata and routing tables, including the list of active shards, database configurations, and chunk-to-shard mapping ranges. Stateless mongos routers cache this metadata to route client queries directly to the appropriate shards without broadcasting.

9. Staff-Level Ready Answer

"A sharded MongoDB cluster consists of independent Shards (data replica sets), a 3-node Config Server replica set (routing metadata catalog), and stateless mongos query routers. Queries with the shard key are targeted directly to the holding shard, while queries without the shard key trigger an expensive scatter-gather broadcast."

10. Quick Knowledge Check

What type of query execution occurs when a client issues a find() query that omits the collection's Shard Key?