{"success":true,"name":"reuse-the-mongodb-connection-one-client-pooled-app-wide","description":"Writing MongoDB connection code or seeing connection errors under load","category":"ai-brimind","path":"ai-brimind/reuse-the-mongodb-connection-one-client-pooled-app-wide/SKILL.md","file":"SKILL.md","content":"---\nname: reuse-the-mongodb-connection-one-client-pooled-app-wide\ndescription: \"Writing MongoDB connection code or seeing connection errors under load\"\n---\n\n# Reuse the MongoDB Connection — One Client, Pooled, App-Wide\n\n## When to use\nProject uses MongoDB (driver or Mongoose), and connection code is being written, duplicated, or failing under load.\n\n## Example request\nCalling MongoClient.connect inside each request handler → a new pool per request; connections explode under load. Mongoose connect called in several files → race conditions on startup; one connect at boot, models imported everywhere else. 'Too many connections' errors → the pool (default ~100) is per client; multiple clients multiply it. Serverless function reconnecting on every invocation → cache the client across invocations; the platform pattern exists for exactly this. Each maps to 'the driver already pools — create one client and share it'.\n\n## Instructions\nAct as an infrastructure-minded developer who knows the MongoDB driver already solves connection management — the job is to not fight it. For connection code: (1) create exactly ONE client/connection at application startup (one MongoClient, or one mongoose.connect), export or inject it, and never connect inside request handlers or loops, (2) trust the built-in pool: the driver reuses sockets automatically; tune maxPoolSize only with evidence, not by reflex, (3) handle the lifecycle deliberately — fail fast and loud if the initial connect fails (an app that boots without its database hides the real problem), and close the client on shutdown, (4) in serverless environments, apply the documented client-caching pattern so warm invocations reuse the connection. If you find multiple connect calls in the codebase, treat that as the root cause of instability before tuning anything else. Only finalize once a single shared, pooled client is confirmed, and explain why connections now scale with the pool, not with traffic.\n\n## Metadata\n- role: developer\n- level: tactical\n- places: vibeCoding\n- origin: ai.brimind.pro skill #1055\n","linked_files":[],"origin":"ai.brimind.pro","owner_id":null,"source":"router"}