/documentdb:documentdb-connectionfrom documentdb
Optimizes MongoDB client connection configuration (pools, timeouts, patterns) for Azure DocumentDB. Covers connection string format, TLS requirements, and driver-specific best practices for Node.js, Python, Java, Go, and C#.
Ships in documentdb. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
You are an expert in MongoDB connection management for Azure DocumentDB across all officially supported driver languages (Node.js, Python, Java, Go, C#, etc.). Your role is to ensure connection configurations are optimized for the user's specific environment and requirements.
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.
Connection Lifecycle:
Borrow from pool → Execute operation → Return to pool → Prune idle connections
exceeding maxIdleTimeMS.
Synchronous vs Asynchronous Drivers:
MongoClient, Java sync): Thread blocks; pool size
often matches thread pool sizeAsyncMongoClient): Non-blocking I/O;
smaller pools sufficePython async note: Use PyMongo's native
AsyncMongoClient(PyMongo 4.9+), not Motor. MongoDB announced Motor's deprecation in May 2024 in favor of PyMongo's built-in async API; Motor receives only critical fixes through May 2026 and is end-of-life after that. New Python async code on Azure DocumentDB should importfrom pymongo import AsyncMongoClient.
Monitoring Connections: Each MongoClient establishes 2 monitoring
connections per replica set member. Formula:
Total = (minPoolSize + 2) × replica members × app instances.
mongodb+srv://<username>:<password>@<cluster-name>.mongocluster.cosmos.azure.com/?tls=true&authMechanism=SCRAM-SHA-256&retryWrites=false
Azure DocumentDB always requires TLS. Ensure:
tls=true in the connection stringSCRAM-SHA-256Before suggesting any configuration changes, ensure you have sufficient context about the user's application environment. If you don't have enough information, ask targeted questions. Ask only one question at a time.
General best practices:
Critical pattern: Initialize client OUTSIDE handler/function scope to enable connection reuse across warm invocations.
| Parameter | Value | Reasoning |
|---|---|---|
maxPoolSize | 3–5 | Each function instance has its own pool |
minPoolSize | 0 | Prevent maintaining unused connections |
maxIdleTimeMS | 10–30s | Release unused connections quickly |
connectTimeoutMS | >0 | Set to longest expected network latency |
socketTimeoutMS | >0 | Ensure sockets are always closed |
// Azure Functions — initialize outside handler
const { MongoClient } = require('mongodb');
const client = new MongoClient(process.env.DOCUMENTDB_URI, {
maxPoolSize: 5,
minPoolSize: 0,
maxIdleTimeMS: 30000,
retryWrites: false,
});
module.exports = async function (context, req) {
const db = client.db('mydb');
const result = await db.collection('items').findOne({});
context.res = { body: result };
};
| Parameter | Value | Reasoning |
|---|---|---|
maxPoolSize | 50+ | Based on peak concurrent requests |
minPoolSize | 10–20 | Pre-warmed connections 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 |
serverSelectionTimeoutMS | 5s | Quick failover |
| Parameter | Value | Reasoning |
|---|---|---|
maxPoolSize | 10–20 | Fewer concurrent operations |
minPoolSize | 0–5 | Queries are infrequent |
socketTimeoutMS | >0 | 2–3× the slowest expected operation |
maxIdleTimeMS | 10min | Minimize churn without keeping idle connections |
| Parameter | Value | Reasoning |
|---|---|---|
maxPoolSize | 100+ | Higher ceiling for sudden traffic spikes |
minPoolSize | 20–30 | More pre-warmed connections |
maxConnecting | 2 (default) | Prevent thundering herd |
waitQueueTimeoutMS | 2–5s | Fail fast when pool exhausted |
maxIdleTimeMS | 5min | Balance reuse and cleanup |
The most important best practice: create ONE MongoClient and reuse it.
// ✅ Good — singleton pattern
let client;
function getClient() {
if (!client) {
client = new MongoClient(process.env.DOCUMENTDB_URI);
}
return client;
}
// ❌ Bad — creating new client per request
app.get('/api/data', async (req, res) => {
const client = new MongoClient(process.env.DOCUMENTDB_URI); // DON'T DO THIS
// ...
await client.close();
});
Symptoms: MongoWaitQueueTimeoutError, increased latency, operations
waiting.
Solutions:
maxPoolSize when: Wait queue has operations waiting + server
shows low utilizationClient Solutions: Increase connectTimeoutMS / socketTimeoutMS if
legitimately needed.
Azure-specific checks:
tls=true)Symptoms: Rapidly increasing connection creation, high CPU from connection handling.
Causes: Not using singleton pattern, not caching client in serverless,
maxIdleTimeMS too low, restart loops.
minPoolSize > 0 for traffic spikescompressors: ['snappy', 'zlib']Azure DocumentDB supports retryable reads. Enable them, and set retryWrites
to false, as Azure DocumentDB connection strings do:
const client = new MongoClient(uri, {
retryReads: true,
retryWrites: false,
});
For transient errors (network blips, failovers), the driver will automatically retry. For application-level retries on specific error codes, implement exponential backoff:
async function withRetry(fn, maxRetries = 3) {
for (let i = 0; i < maxRetries; i++) {
try {
return await fn();
} catch (err) {
if (i === maxRetries - 1) throw err;
if (err.code === 16500 || err.code === 429) {
// Rate limited — wait and retry
const waitMs = Math.min(1000 * Math.pow(2, i), 30000);
await new Promise(r => setTimeout(r, waitMs));
} else {
throw err; // Non-retryable error
}
}
}
}
ALWAYS verify you have sufficient context about the user's application before suggesting configuration changes.
Guidelines:
For every connection parameter you provide, ensure you have enough context about the user's application to justify the values. If not, ask targeted questions first. If you get no answer, make a reasonable assumption, disclose it, and comment the relevant parameters in the code.
What SKILL.md sets; muted values are Claude Code's defaults
npx claudepluginhub azure/documentdb-agent-kit --plugin documentdb17 skills in this plugin
/documentdb-azure-deploymentDeploy an Azure DocumentDB cluster (`Microsoft.DocumentDB/mongoClusters`) end-to-end — Bicep (primary), Azure CLI (`documentdb` extension), Terraform, or the Azure portal. Every step has a scriptable command, so it works the same for a developer at a terminal, a CI pipeline, or a coding agent. Covers resource-group creation, cluster parameters (tier, storage, server version, sharding, HA), firewall rule configuration, retrieving the connection string, and teardown. Use when the user asks to provision, create, deploy, or spin up an Azure DocumentDB cluster, or wants infrastructure-as-code for one./documentdb-data-modelingData modeling patterns for Azure DocumentDB — embed vs reference, 16 MB document limit, denormalization for read-heavy workloads, schema versioning. Use when designing new schemas, reviewing existing data models, migrating from SQL, deciding between embedding and referencing, modeling one-to-one / one-to-many / many-to-many relationships, or troubleshooting document-size and query-performance problems that stem from the data model./documentdb-driverMongoDB driver and SDK best practices for Azure DocumentDB — singleton `MongoClient`, connection reuse, connection-pool fundamentals. Use when writing code that instantiates a MongoDB client, reviewing driver initialization, or diagnosing connection-related bugs. For full connection-pool tuning (serverless vs OLTP vs OLAP, timeouts, retries), see the `documentdb-connection` skill./documentdb-full-text-searchFull-text search best practices for Azure DocumentDB using the `createSearchIndexes` command and `$search` aggregation stage — BM25 keyword scoring, fuzzy search (`maxEdits`), phrase search with `slop`, custom analyzers (keyword + lowerCase + asciiFolding + edgeGram) for prefix / ID matching, `pathHierarchy` tokenizer for hierarchical IDs, multi-field search indexes, and hybrid (BM25 + vector) retrieval via Reciprocal Rank Fusion. Use when building search experiences, adding typo tolerance, matching phrases or prefixes on IDs / SKUs / part numbers, or combining lexical and semantic retrieval on the same collection./documentdb-high-availabilityHigh availability, business-continuity, and disaster-recovery best practices for Azure DocumentDB — enabling in-region HA with availability zones (99.99% SLA), adding active-passive cross-region replica clusters (99.995% SLA), and understanding automatic backup retention. Use when designing production topology, planning failover, provisioning DR, picking regions, or reviewing cluster architecture./documentdb-indexingIndex-type selection and shape guidance for Azure DocumentDB — when to use single-field, compound (ESR), multikey, wildcard, hashed, 2dsphere, TTL, and vector indexes; query-pattern → index-shape cookbook; per-collection index budget; DocumentDB-specific preference for `textSearch` over community `$text`. Use when designing or reviewing indexes, choosing an index type for a query pattern, or deciding whether an additional index is worth the write cost.Other plugins' skills for the same job