選項
首頁首頁 Skill 資料庫管理 mongodb-connection

mongodb-connection

mongodb/agent-skills mongodb/agent-skills

針對任何受支援的驅動程式語言,最佳化 MongoDB 客戶端連線設定(連線池、超時設定、模式)。 在處理、更新或審查會實例化或配置 MongoDB 客戶端的功能時(例如呼叫 `connect()`),請運用此技能;亦適用於配置連線池、排除連線錯誤(如 ECONNREFUSED、超時、連線池耗盡),以及優化與連線相關的效能問題。 這包括以下情境:使用 MongoDB 建置無伺服器函式、建立 API 端點

...展開全部
14
更新時間 2026-08-23

關於《mongodb-connection》

這是一項涵蓋所有官方支援驅動程式語言(Node.js、Python、Java、Go、C#、Ruby、PHP 及其他)之 MongoDB 連線優化技能,內容包含客戶端連線設定——連線池、超時設定及實例化模式。 此技能適用於以下情境:開發或配置 MongoDB 客戶端、建立連線池、排除 ECONNREFUSED 等連線錯誤、處理超時或連線池耗盡問題,以及優化與連線相關的效能。 典型情境包括無伺服器函式、API 端點、高流量應用程式、具有並發性的長期執行任務,以及除錯連線失敗。

其核心原則是「情境優先於設定」:在未先了解應用程式環境之前,切勿新增連接池參數或超時設定,因為隨意的數值會導致效能問題及難以除錯的狀況。 書中闡述了連接池的工作原理(TCP、TLS 及身份驗證的連線建立約需 50–500 毫秒,且每個開啟的連線即使處於閒置狀態,也會消耗約 1 MB 的伺服器 RAM),由 `maxIdleTimeMS` 所規管的「借用/執行/歸還/清理」生命週期, 以及同步驅動程式(其池大小通常與執行緒池相符)與非同步驅動程式(較小的池即已足夠)之間的差異。文中透過公式「總數 = (minPoolSize + 2) × 複製集成員數 × 應用程式實例數」,說明了每個複製集成員會自動監控的兩個連線。

實務指引包括根據吞吐量和延遲計算初始池大小(池大小 ≈ 每秒操作次數 × 平均持續時間 + 10–20% 的緩衝值)、在持續時間波動時採取保守起始值,以及考量拓撲結構: 連接池是按每台伺服器、每個客戶端建立的;分片叢林通常透過 mongos 路由器連接;而次要讀取偏好設定可能會為每個成員增加一個連接池。本文建議採用最佳實務,例如僅建立一次客戶端並重複使用(在無伺服器架構中於處理程序外初始化)、除關機時外不手動關閉連接,以及將最大連接池大小維持在預期並發量之上。 文中提供了針對無伺服器環境(小型連接池、minPoolSize 設為 0、短暫閒置時間)、長期運行的 OLTP 伺服器(較大連接池、預暖連線、快速失敗的超時設定)以及 OLAP/分析型工作負載的參數調整表格,每項建議值皆依據蒐集到的背景資訊進行合理說明。

常見問題

何時該使用此技能?

適用於實例化或配置 MongoDB 客戶端、設定連接池、排除 ECONNREFUSED、超時或連接池耗盡等連接錯誤,或針對無伺服器、高流量或長期運行工作負載優化連接效能。

其配置的主要原則是什麼?

先了解情境,再進行配置:在充分理解應用程式環境之前,切勿直接設定連接池或超時參數。本工具會先從宏觀層面著手,逐一提出針對性問題,然後才提供建議值。

如何決定連線池的大小?

若有效能數據,請使用「連接池大小 ≈ (每秒操作次數) × (平均持續時間)」,並加上 10–20% 的緩衝值。若持續時間不固定,建議先保守地設定為 10–20 個連接,並持續監控與調整。

它如何建議配置無伺服器函式?

請在處理程序外部初始化客戶端,以便在「暖機」調用間重複使用連線;並設定較小的 maxPoolSize(3–5)、minPoolSize 為 0,以及較短的 maxIdleTimeMS(10–30 毫秒),同時確保連線和套接字超時設定為非零值。

它是否會考慮超出連接池的連接數量?

是的。每個 MongoClient 會針對每個副本集成員新增兩條監控連線,因此潛在的總連線數約為:執行個體數 × (maxPoolSize + 2) × 副本集成員數。建議監控 `connections.current` 以避免觸及伺服器限制。

所有檔案

2 個檔案references/monitoring-guide.md8.4 KB檢視SKILL.md13.6 KB檢視
在 GitHub 上查看

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:

ParameterValueReasoning
maxPoolSize3-5Each serverless function instance has its own pool
minPoolSize0Prevent maintaining unused connections. Increase to mitigate cold starts if needed
maxIdleTimeMS10-30sRelease unused connections more quickly
connectTimeoutMS>0Set to a value greater than the longest network latency you have to a member of the set
socketTimeoutMS>0Use socketTimeoutMS to ensure that sockets are always closed
Scenario: Traditional Long-Running Servers (OLTP Workload)

Recommended configuration:

ParameterValueReasoning
maxPoolSize50+Based on peak concurrent requests (monitor and adjust)
minPoolSize10-20Pre-warmed connections ready for traffic spikes
maxIdleTimeMS5-10minStable servers benefit from persistent connections
connectTimeoutMS5-10sFail fast on connection issues
socketTimeoutMS30sPrevent hanging queries; appropriate for short OLTP operations
serverSelectionTimeoutMS5sQuick 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:

ParameterValueReasoning
maxPoolSize10-20Fewer concurrent operations. Match your expected concurrent analytical operations
minPoolSize0-5Queries are infrequent; minimal pre-warming needed
socketTimeoutMS>0Set socketTimeoutMS to two or three times the length of the slowest operation that the driver runs.
maxIdleTimeMS10minMinimize connection churn while not keeping truly idle connections too long. Consider the timeouts of intermediate network devices
Scenario: High-Traffic / Bursty Workloads

Recommended configuration:

ParameterValueReasoning
maxPoolSize100+Higher ceiling to accommodate sudden traffic spikes
minPoolSize20-30More pre-warmed connections ready for immediate bursts
maxConnecting2 (default)Prevent thundering herd during sudden demand
waitQueueTimeoutMS2-5sFail fast when pool exhausted rather than queueing indefinitely
maxIdleTimeMS5minBalance 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.md for 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 maxPoolSize when: Wait queue has operations waiting (size > 0) + server shows low utilization
  • Don'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 spikes
  • Network 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.

所有檔案

0 個檔案

安裝 mongodb-connection

請下載技能檔案,並將其解壓縮至您的 .claude/skills/ 目錄中。

下載 ZIP

複製儲存庫並將技能檔案複製到您的專案中。

git clone https://github.com/mongodb/agent-skills/blob/main/skills/mongodb-connection/SKILL.md # Copy SKILL.md to your .claude/skills/ directory

複製 複製
快速設定: 將技能資料夾複製到 .claude/skills/,Claude 將會自動偵測並使用該技能

相關技能

microservices-patterns
更新時間 2026-06-29
jpa-patterns
更新時間 2026-06-30
fabric-lakehouse
更新時間 2026-06-30
prisma-expert
更新時間 2026-06-29
OR