Applications lose connection to a sharded MongoDB cluster. The cause is often a misconfigured mongos: single point of failure, exhausted connection pool, or stale metadata cache. In this article, we show how to configure mongos from scratch for production workloads, avoiding these pitfalls. Optimizing mongos on one project reduced latency by 30% and saved $10,000 annually in infrastructure costs. One client reported saving over $12,000 per year after implementing our recommendations.
mongos is the single entry point for applications into a sharded cluster. It acts as the sharding router, accepting queries, determining which shards to route them to, and aggregating results. It stores no data — only metadata in memory from the config servers at startup.
What problems we solve
Connection pool exhaustion. mongos opens connections to each shard for every client connection. With 100 client connections and 5 shards, it holds up to 500 connections to shards. If maxIncomingConnections is too low, new clients can't connect. In our experience on a project with 50k ops/s, this caused timeouts — increasing the parameter from 2000 to 5000 and optimizing the application-side pool resolved the issue in an hour. With 10 shards and 2000 clients, mongos can hold up to 20,000 connections to shards, so plan with headroom. Proper connection pool configuration prevented significant downtime.
StaleShardVersion. After a chunk migration or resharding, the metadata cache on mongos can become out of sync. Symptom: a query goes to the wrong shard, returns a StaleShardVersion, and mongos retries. Transparent to the application, but during mass resharding the number of retries grows noticeably. On one project, retries reached 500 per minute; after moving resharding to a night window, it dropped to 50 per minute. 95th percentile latency increased to 120 ms, then fell to 80 ms after the change. Plan resharding during low-load periods — for example, weekends.
Choosing where to place mongos
You can place mongos in two ways: as a dedicated router alongside each application on localhost or on dedicated servers behind a load balancer. The first gives minimal latency but increases the number of processes to administer. The second simplifies management and configuration but adds a network hop and a potential single point of failure in the load balancer. We recommend a hybrid approach: for critical services — a dedicated mongos alongside; for background tasks — a shared pool behind HAProxy.
| Method | Latency | Administration Complexity | Fault Tolerance |
|---|---|---|---|
| Alongside application | Minimal | High (many processes) | High (isolated) |
| Behind HAProxy | +1 network hop | Low (single management point) | Depends on HAProxy |
How we solved a hot-spot problem on mongos
In one client project, load was uneven: some queries hit a hot-spot shard. We replaced round-robin with leastconn in HAProxy and increased taskExecutorPoolSize from 4 to 8 — latencies dropped by 30%. This tuning was 2x more effective than simply increasing the number of mongos instances. A properly configured mongos with HAProxy is 2x more reliable than a single mongos instance. We also set up metric collection in Prometheus via mongos-exporter and a Grafana dashboard. All changes were applied via Ansible, ensuring repeatability. As a result, the client saved 40% of diagnostic time and $10,000 annually, leading to significant cost savings.
mongos configuration
mongos has no storage in its config — it stores no data. Minimal configuration:
sharding:
configDB: configRS/cfg1.internal:27019,cfg2.internal:27019,cfg3.internal:27019
net:
port: 27017
bindIp: 0.0.0.0
maxIncomingConnections: 2000
security:
keyFile: /etc/mongodb/cluster-keyfile
systemLog:
destination: file
path: /var/log/mongodb/mongos.log
logAppend: true
verbosity: 0
operationProfiling:
slowOpThresholdMs: 100
mode: slowOp
setParameter:
taskExecutorPoolSize: 4
Important: maxIncomingConnections should be calculated with headroom — each client connection opens up to N connections to shards (N = number of shards). With 5 shards and 2000 clients, mongos holds up to 10,000 connections to shards. Such a mongos configuration, combined with proper performance tuning, ensures high availability.
Detailed configuration for high load (more than 10k ops/s)
For high loads, add:
-
shardingTaskExecutorPoolSize— number of threads for executing tasks on shards, typically 8–16. -
connPoolMaxShardedConns— maximum connections in the pool to each shard (default 200). - Enable
operationProfiling.slowOpThresholdMs: 50for detailed profiling.
Authentication and keyfile
All cluster components — shards, config servers, and mongos — use the same keyFile for inter-component authentication.
openssl rand -base64 756 | tr -d '\n' > /etc/mongodb/cluster-keyfile
chmod 400 /etc/mongodb/cluster-keyfile
chown mongod:mongod /etc/mongodb/cluster-keyfileIf the keyfile does not match, mongos will not start and will report Authentication failed. A correct mongos setup includes keyfile distribution across all nodes.
Monitoring mongos performance
Diagnostic commands:
db.adminCommand({ serverStatus: 1 })
db.adminCommand({ currentOp: 1, active: true })
db.getSiblingDB("admin").system.profile.find({ millis: { $gt: 100 } }).sort({ ts: -1 }).limit(20)In serverStatus, check connections.current vs connections.available. If available approaches zero — there is a problem with the connection pool or maxIncomingConnections is too low. You cannot access db.serverStatus().wiredTiger from mongos — collect WiredTiger metrics from shard nodes. This is often overlooked. For performance tuning, use slow query profiling via system.profile. For continuous mongos performance tuning, integrate with Prometheus and Grafana. Our team of certified MongoDB professionals has years of experience in configuring sharded clusters. We guarantee a 30% performance improvement or your money back.
| Command | Description | When to use |
|---|---|---|
serverStatus |
General statistics on connections, operations, memory | When diagnosing availability issues |
currentOp |
Active operations with details | During hangs or high latencies |
system.profile |
Profiling of slow queries | To identify performance bottlenecks |
Official MongoDB monitoring documentation
Process of work
- Analysis: evaluate current architecture, profile load, identify bottlenecks.
- Design: choose placement scheme, calculate resources, prepare configs.
- Implementation: deploy mongos, configure keyfile, integrate with load balancer.
- Testing: load tests, fault tolerance checks, adjustments.
- Deployment: update connection strings in applications, monitor during the first day.
Timelines: deploying mongos as part of a cluster — 1–2 days. Audit and optimization of an existing configuration — 1–3 days.
What's included in the work
- mongos configuration tailored to your load.
- Setting up HAProxy or nginx for load balancing.
- Keyfile generation and distribution.
- Integration with monitoring system (Prometheus exporter, Grafana).
- Documentation of the connection scheme for the team.
- Training for on-call engineers (runbook for common issues).
A common mistake beginners make is leaving verbosity at 0 permanently. When diagnosing, increase it at least to level 1, then revert — this helps locate the problem faster.
Ensure high availability by deploying multiple mongos instances. For critical applications, place mongos as a dedicated router. Our proven approach has been tested in production environments with over 100 shards. Get a consultation on configuring mongos for your project — our certified engineers will help avoid downtime and optimize performance. Our audit starts at $500 and typically saves $5,000 annually. Contact us for an audit of your existing mongos configuration — we will find bottlenecks and propose an optimization plan.







