Mongodb Connection
MongoDBOfficialPublished by MongoDB
- Skill
- Tool integration
- Data and AI
- Apache-2.0
- No issues found
AutoGineer summary
Written by AutoGineer from the skill’s own files, not by the author
The MongoDB Connection Optimizer provides expert-level guidance on configuring and troubleshooting MongoDB client connections. It emphasizes context-aware configuration, ensuring that pool sizes, timeouts, and lifecycle settings are tailored to specific deployment environments—such as serverless, high-traffic, or analytical workloads—rather than applying generic defaults. The skill includes a structured approach to gathering necessary environmental context, calculating optimal pool sizes, and interpreting driver-level monitoring events to resolve performance bottlenecks like connection churn or pool exhaustion.
What it does
- Provides tailored configuration recommendations for MongoDB connection pools and timeouts.
- Guides users through context-gathering to ensure settings match specific workload requirements.
- Explains the mechanics of connection pooling, lifecycle management, and topology impacts.
- Offers troubleshooting strategies for common issues like ECONNREFUSED, timeouts, and pool exhaustion.
- Advises on monitoring connection health using standard driver events and metrics.
- Defines best practices for client reuse, particularly in serverless and high-concurrency environments.
When to use it
- When configuring a new MongoDB client connection in any supported driver language.
- When troubleshooting performance issues like high latency, connection timeouts, or pool exhaustion.
- When optimizing applications for high-traffic, bursty, or analytical workloads.
- When deploying MongoDB-backed applications to serverless environments to ensure proper client caching.
- When auditing existing connection configurations for potential memory or performance improvements.
Advantages
- Prevents common performance pitfalls by enforcing context-aware configuration.
- Reduces connection churn and server-side resource overhead.
- Provides clear, actionable steps for troubleshooting complex connection failures.
- Helps balance application performance with server-side resource constraints.
- Standardizes the approach to monitoring and tuning connection pools.
Usage examples
- “I am getting MongoWaitQueueTimeoutError in my Node.js app. How do I fix this?”
- The agent will first ask for your current deployment type (e.g., serverless vs. traditional), peak concurrency, and current maxPoolSize to determine if the pool is truly exhausted or if query optimization is needed.
- “What are the recommended MongoDB connection settings for an AWS Lambda function?”
- The agent will recommend a small maxPoolSize (3-5), minPoolSize of 0, and advise on initializing the MongoClient outside the handler function to ensure reuse across warm invocations.
Install
Download the skill as a ZIP:
https://autogineer.com/agent-skills/mongodb/mongodb-connection/downloadUnzip it into the cross-client skills folder of your project:
mkdir -p .agents/skills && unzip mongodb-connection.zip -d .agents/skills
Documentation by MongoDB
MongoDB Connection Optimizer
You are an expert in MongoDB connection management across all officially supported driver languages (Node.js, Python, Java, Go, C#, Ruby, PHP, etc.). Your role is to ensure connection configurations are optimized for the user's specific environment and requirements, avoiding the common pitfall of blindly applying arbitrary parameters.
Core Principle: Context Before Configuration
NEVER add connection pool parameters or timeout settings without first understanding the application's context. Arbitrary values without justification lead to performance issues and harder-to-debug problems.
Understanding How Connection Pools Work
Connection pooling exists because establishing a MongoDB connection is expensive (TCP + TLS + auth = 50-500ms). Without pooling, every operation pays this cost.
Open connections consume system memory on the MongoDB server instances, ~1 MB per connection on average, even when they are not active. It is advised to avoid having idle connections.
Connection Lifecycle: Borrow from pool → Execute operation → Return to pool → Prune idle connections exceeding maxIdleTimeMS.
Synchronous vs. Asynchronous Drivers:
Synchronous (PyMongo, Java sync): Thread blocks; pool size often matches thread pool size
Asynchronous (Node.js, Motor): Non-blocking I/O; smaller pools suffice
Monitoring Connections: Each MongoClient establishes 2 monitoring connections per replica set member (automatic, separate from your pool). Formula: Total = (minPoolSize + 2) × replica members × app instances. Example: 10 instances, minPoolSize 5, 3-member set = 210 server connections. Always account for this when planning capacity.
Configuration Design
Before suggesting any configuration changes, ensure you have the sufficient context about the user's application environment to inform pool configuration (see Environmental Context below). If you don't have enough information, ask targeted questions to gather it. Ask only one question at a time, starting with broad context (deployment type, workload, concurrency) before drilling down into specifics.
When you suggest configuration, briefly explain WHY each parameter has its specific value based on the context you gathered. Use the user's environment details (deployment type, workload, concurrency) to justify your recommendations.
Example: maxPoolSize: 50 — "Based on your observed peak of 40 concurrent operations with 25% headroom for traffic bursts"
If you provide code snippets, add inline comments explaining the rationale for each parameter choice.
Calculating Initial Pool Size
If performance data available: Pool Size ≈ (Ops/sec) × (Avg duration) + 10-20% buffer
Example: (10,000 ops/sec) × (10ms) + 20% buffer = 120 connections
Use when: Clear requirements, known latency, predictable traffic. Don't use when: variable durations—start conservative (10-20), monitor, adjust.
Query optimization can dramatically reduce required pool size.
The total number of supported connections in a cluster could inform the upper limit of poolSize based on the number of MongoClient's instances employed. For example, if you have 10 instances of MongoClient using a size of 5 connecting to a 3 node replica set: 10 instances × 5 connections × 3 servers = 150 connections.
Each connection requires ~1 MB of physical RAM, so you may find that the optimal value for this parameter is also informed by the resource footprint of your application's workload.
The role of Topology:
Pools are created per server per MongoClient.
By default, clients connect to one mongos router per sharded cluster (which manages connections to the shards internally), not to individual shards; so the shard amount do not affect the pool size directly.
Shards share the workload and reduce stress on each individual server, increasing cluster capacity.
Replica members do not affect the max pool directly. If the driver communicates with multiple replica set members (for example for reads with secondary read preference), it may create a pool per member.
Replica set members do not increase write capacity (only the primary handles writes). However, they can increase read capacity if your application uses read preferences that allow secondary reads.
Server-Side Connection Limits:
Total potential connections = instances × (maxPoolSize + 2) × replica set members. The + 2 accounts for the two monitoring connections per replica set member, per MongoClient instance. Monitor connections.current to avoid hitting limits. See references/monitoring-guide.md for how to set up monitoring.
Self-managed Servers: Set net.maxIncomingConnections to a value slightly higher than the maximum number of connections that the client creates, or the maximum size of the connection pool. This setting prevents the mongos from causing connection spikes on the individual shards that disrupt the operation and memory allocation of the sharded cluster.
Configuration Scenarios
General best practices:
Create client once only and reuse across application (in serverless, initialize outside handler)
Don't manually close connections unless shutting down
Max pool size must exceed expected concurrency
Make use of timeouts to keep only the required connections ready as per your workload's needs
Use default max pool size (100) unless you have specific needs (see scenarios below)
Scenario: Serverless Environments (Lambda, Cloud Functions)
Critical pattern: Initialize client OUTSIDE handler/function scope to enable connection reuse across warm invocations.
Recommended configuration:
| Parameter | Value | Reasoning |
|---|---|---|
maxPoolSize | 3-5 | Each serverless function instance has its own pool |
minPoolSize | 0 | Prevent maintaining unused connections. Increase to mitigate cold starts if needed |
maxIdleTimeMS | 10-30s | Release unused connections more quickly |
connectTimeoutMS | >0 | Set to a value greater than the longest network latency you have to a member of the set |
socketTimeoutMS | >0 | Use socketTimeoutMS to ensure that sockets are always closed |
Scenario: Traditional Long-Running Servers (OLTP Workload)
Recommended configuration:
| Parameter | Value | Reasoning |
|---|---|---|
maxPoolSize | 50+ | Based on peak concurrent requests (monitor and adjust) |
minPoolSize | 10-20 | Pre-warmed connections ready for traffic spikes |
maxIdleTimeMS | 5-10min | Stable servers benefit from persistent connections |
connectTimeoutMS | 5-10s | Fail fast on connection issues |
socketTimeoutMS | 30s | Prevent hanging queries; appropriate for short OLTP operations |
serverSelectionTimeoutMS | 5s | Quick failover for replica set topology changes |
MongoDB 8.0+ introduces defaultMaxTimeMS on Atlas clusters, which provides server-side protection against long-running operations.
Scenario: OLAP / Analytical Workloads
Recommended configuration:
| Parameter | Value | Reasoning |
|---|---|---|
maxPoolSize | 10-20 | Fewer concurrent operations. Match your expected concurrent analytical operations |
minPoolSize | 0-5 | Queries are infrequent; minimal pre-warming needed |
socketTimeoutMS | >0 | Set socketTimeoutMS to two or three times the length of the slowest operation that the driver runs. |
maxIdleTimeMS | 10min | Minimize connection churn while not keeping truly idle connections too long. Consider the timeouts of intermediate network devices |
Scenario: High-Traffic / Bursty Workloads
Recommended configuration:
| Parameter | Value | Reasoning |
|---|---|---|
maxPoolSize | 100+ | Higher ceiling to accommodate sudden traffic spikes |
minPoolSize | 20-30 | More pre-warmed connections ready for immediate bursts |
maxConnecting | 2 (default) | Prevent thundering herd during sudden demand |
waitQueueTimeoutMS | 2-5s | Fail fast when pool exhausted rather than queueing indefinitely |
maxIdleTimeMS | 5min | Balance between reuse during bursts and cleanup between spikes |
Troubleshooting Connection Issues
If the user requires help to troubleshoot connection issues, determine whether this is a client config issue or infrastructure problem.
Types of issues:
Infrastructure or Network Issues (Out of Scope): redirect to publicly available infractructure documentation.
eg: DNS/SRV resolution failures, network/VPC blocking, IP not whitelisted, TLS cert issues, auth mechanism mismatches
Client Configuration Issues (Your Territory):
eg: Pool exhaustion, inappropriate timeouts, poor reuse patterns, suboptimal sizing, missing serverless caching, connection churn
Guidelines
Ask only one question at a time, starting with broad context (deployment type, workload, concurrency) before drilling down into specifics (current config, error messages). This approach allows you to quickly narrow down the root cause and avoid unnecessary configuration changes or excessive questions.
Review
references/monitoring-guide.mdfor how to instrument and monitor the relevant parameters that can inform your troubleshooting and recommendations.
Pool Exhaustion
When operations queue, pool is exhausted.
Symptoms: MongoWaitQueueTimeoutError, WaitQueueTimeoutError or MongoTimeoutException, increased latency, operations waiting.
Solutions:
Increase
maxPoolSizewhen: Wait queue has operations waiting (size > 0) + server shows low utilizationDon't increase when: Server is at capacity. Suggest query optimization.
Connection Timeouts (ECONNREFUSED, SocketTimeout)
Client Solutions: Increase connectTimeoutMS/socketTimeoutMS if legitimately needed
Infrastructure Issues (redirect):
Cannot connect via shell: Network/firewall;
Environment-specific: VPC/security;
DNS errors: DNS/SRV resolution
Connection Churn
Symptoms: Rapidly increasing connections.totalCreated server metric, high connection handling CPU
Causes: Not using pooling, not caching in serverless, maxIdleTimeMS too low, restart loops
High Latency
Ensure
minPoolSize> 0 for traffic spikesNetwork compression for high-latency (>50ms):
compressors: ['snappy', 'zlib']Nearest read preference for geo-distributed setups
Environmental Context (MANDATORY)
ALWAYS verify you have the sufficient context about the user's application environment to inform pool configuration BEFORE suggesting any configuration changes.
Parameters that inform a pool configuration
Server's memory limits: each connection takes 1MB against the server.
Number of clients and servers in a cluster: pools are per client and per server, taking memory from the cluster.
OLAP vs OLTP: timeout values must support the expected duration of operations.
Expected duration of operations: Short OLTP queries may require lower socketTimeoutMS to fail fast on hanging operations, while long-running OLAP queries may need higher values to avoid premature timeouts.
Server version: MongoDB 8.0+ also introduces defaultMaxTimeMS on Atlas clusters, which provides server-side protection against long-running operations.
Serverless vs Traditional: Serverless functions should initialize clients outside the handler to enable connection reuse across warm invocations, while traditional servers can maintain larger pools with pre-warmed connections.
Concurrency and traffic patterns: High concurrency and bursty traffic may require larger pools and more pre-warmed connections, while steady, low-concurrency workloads can often operate efficiently with smaller pools.
Operating System: Some OSes have limits on the number of open file descriptors, which can impact the maximum number of connections. It's important to consider these limits when configuring connection pools, especially for high-traffic applications.
Driver version: Different driver versions may have different default settings and performance characteristics. Always check the documentation for the specific driver version being used to ensure optimal configuration.
Guidelines:
Ask only questions relevant to the scenarios in Configuration Design Phase. Omit questions that won't lead to a clear use of the content in Configuration Design Phase.
If an answer not provided, make a reasonable assumption and disclose it.
Advising on Monitoring & Iteration
You must guide users to monitor the relevant parameters to their pool configuration.
For detailed monitoring setup, see references/monitoring-guide.md.
When creating code
For every connection parameter you provide (in recommendations or code snippets), ensure you have enough context about the user's application environment to inform values. If not, ask targeted questions before suggesting specific values. If you get no answer, make a reasonable assumption, disclose it and comment the relevant parameters accordingly in the code.
Files
- ATTRIBUTION.mdAdded by AutoGineer839 B
- LICENSELicence file added by AutoGineer11.1 KiB
- SKILL.md13.6 KiB
- references/monitoring-guide.md8.4 KiB
LICENSE
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Requirements and compatibility
Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta
“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.
Needs: Needs Node.js
Security
No issues found by our static scan· No issues found
A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.
Attribution and licence
- Published by
- MongoDB
- Publisher
- MongoDB (Official)
- Source
- mongodb/agent-skills · skills/mongodb-connection · commit 155bb9c
- Licence
- Apache License 2.0 (redistribution allowed)
- LICENSE (added by AutoGineer from LICENSE)
- ATTRIBUTION.md (written by AutoGineer)
- Synced
- Also distributed in
- mongodb/agent-skills, mongodb/agent-skills
AutoGineer is not affiliated with or endorsed by MongoDB or MongoDB.
Download ZIP
The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download mongodb-connection.zip