옵션
집 Skill 데이터베이스 관리 mongodb-connection

mongodb-connection

mongodb/agent-skills mongodb/agent-skills

지원되는 모든 드라이버 언어에 맞게 MongoDB 클라이언트 연결 설정(풀, 타임아웃, 패턴)을 최적화합니다. MongoDB 클라이언트를 인스턴스화하거나 설정하는 함수(예: connect() 호출 시)를 작성하거나 업데이트하거나 검토할 때, 연결 풀을 구성하거나 연결 오류(ECONNREFUSED, 타임아웃, 풀 고갈)를 해결하거나 연결과 관련된 성능 문제를 개선할 때 이 기술을 활용할 수 있습니다. 여기에는 MongoDB를 활용한 서버리스 함수 구축이나 API 생성과 같은 시나리오도 포함됩니다.

...모든 것을 확장하십시오
14
업데이트 된 시간 2026년 8월 23일

MongoDB 연결에 관하여

모든 공식적으로 지원되는 드라이버 언어(Node.js, Python, Java, Go, C#, Ruby, PHP 등)를 대상으로 클라이언트 연결 설정—풀, 타임아웃, 인스턴스화 패턴—을 다루는 MongoDB 연결 최적화 기술입니다. 이 기술은 MongoDB 클라이언트를 생성하거나 설정하고, 연결 풀을 구성하며, ECONNREFUSED, 타임아웃, 풀 고갈과 같은 연결 오류를 해결하거나 연결 관련 성능을 최적화하는 코드 작업에 적용됩니다. 일반적인 사용 사례로는 서버리스 함수, API 엔드포인트, 트래픽이 많은 애플리케이션, 동시성이 필요한 장시간 실행 작업, 연결 실패 디버깅 등이 있습니다.

이 기술의 핵심 원칙은 설정에 앞서 상황을 먼저 파악하는 것입니다. 애플리케이션의 환경을 미리 이해하지 않고서는 절대로 풀 매개변수나 타임아웃 설정을 추가해서는 안 되며, 임의로 지정된 값은 성능 문제나 디버깅이 어려운 문제를 야기하기 때문입니다. 또한 TCP, TLS 연결 설정 및 인증에 약 50~500ms의 시간이 소요되며, 비활성 상태일 때도 각 열린 연결이 서버 RAM의 약 1MB를 사용한다는 점, maxIdleTimeMS에 의해 관리되는 대출/실행/반환/제거 라이프사이클, 동기식 드라이버(풀 크기가 보통 스레드 풀 크기와 일치)와 비동기식 드라이버(작은 풀 크기로도 충분함)의 차이점 등에 대해서도 설명합니다. 또한 복제 세트의 각 멤버당 자동으로 생성되는 2개의 모니터링 연결에 대해서는 Total = (minPoolSize + 2) × replica members × app instances라는 공식을 통해 설명합니다.

실용적인 가이드라인으로는 처리량과 지연 시간을 바탕으로 초기 풀 크기를 계산하는 방법(Pool Size ≈ ops/sec × avg duration + 10–20% 버퍼), 지속 시간이 변동될 경우 보수적으로 시작하는 방법, 그리고 토폴로지 고려 사항(서버당 클라이언트별로 풀을 생성, 샤딩된 클러스터는 일반적으로 mongos 라우터를 통해 연결, 보조 읽기 선호도로 인해 멤버당 풀이 추가됨) 등이 있습니다. 또한 서버리스 환경에서는 클라이언트를 한 번 생성해 반복적으로 재사용하고(서버리스의 핸들러 외부에서 초기화), 종료 시가 아닌 경우에는 수동으로 연결을 닫지 않으며, 예상되는 동시 접속 수보다 높은 최대 풀 크기를 유지하는 것과 같은 모범 사례도 권장합니다. 서버리스(작은 풀, minPoolSize 0, 짧은 비활성 시간), 장시간 실행되는 OLTP 서버(큰 풀, 사전 예열된 연결, 빠른 실패 타임아웃), OLAP/분석 작업 부하에 맞춘 최적화된 매개변수 표도 제공되며, 각 권장 값은 수집된 정보를 바탕으로 정당화됩니다.

자주 묻는 질문

이 기술은 언제 사용해야 하나요?

MongoDB 클라이언트를 인스턴스화하거나 설정하고, 연결 풀을 구성하며, ECONNREFUSED, 타임아웃, 풀 고갈과 같은 연결 오류를 해결하거나, 서버리스, 트래픽이 많은 환경, 장시간 실행 작업의 연결 성능을 최적화할 때 이 기술을 사용합니다.

설정과 관련된 주요 규칙은 무엇인가요?

설정에 앞서 상황을 먼저 파악하는 것입니다. 애플리케이션의 환경을 미리 이해하지 않고서는 절대로 풀이나 타임아웃 매개변수를 추가해서는 안 됩니다. 권장 값을 제시하기 전에 먼저 광범위한 질문부터 하나씩 묻습니다.

연결 풀의 크기는 어떻게 결정해야 하나요?

성능 데이터가 있는 경우 Pool Size ≈ (ops/sec) × (avg duration) + 10–20% 버퍼 공식을 사용합니다. 지속 시간이 변동될 경우에는 10~20개의 연결로 보수적으로 시작한 뒤 모니터링을 통해 조정합니다.

서버리스 함수의 설정은 어떻게 권장하나요?

연결을 반복적으로 재사용하기 위해 핸들러 외부에서 클라이언트를 초기화하고, 작은 maxPoolSize(3~5), minPoolSize 0, 짧은 maxIdleTimeMS(10~30초)를 사용하며, connect 및 socket 타임아웃 값을 0이 아닌 값으로 설정하는 것을 권장합니다.

풀 외의 연결도 고려하나요?

네. 각 MongoClient는 복제 세트의 각 멤버당 2개의 모니터링 연결을 추가하므로, 총 잠재적 연결 수는 대략 instances × (maxPoolSize + 2) × replica members가 됩니다. 서버의 제한을 초과하지 않도록 connections.current를 모니터링할 것을 권장합니다.

All Files

2 filesreferences/monitoring-guide.md8.4 KBViewSKILL.md13.6 KBView

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년 6월 29일
jpa-patterns
업데이트 된 시간 2026년 6월 30일
fabric-lakehouse
업데이트 된 시간 2026년 6월 30일
PostgreSQL Syntax Reference
업데이트 된 시간 2026년 6월 29일
OR