This prompt is designed for backend reliability engineers and SREs actively investigating a production incident where the primary symptom is database connection pool saturation. The ideal user has access to real-time or recent pool metrics (active, idle, pending counts), query latency percentiles, and the application source code responsible for managing the connection lifecycle. The core job-to-be-done is to move beyond surface-level metrics and correlate runtime signals with specific code patterns—such as connections opened but not closed in a finally block, transactions held open across an external API call, or a missing connection timeout setting—to identify the precise leak source or bottleneck. The prompt instructs an AI coding agent to perform this correlation and produce a concrete, actionable remediation plan, including a data-driven pool sizing recommendation.
Prompt
Database Connection Pool Exhaustion Prompt

When to Use This Prompt
Defines the precise conditions, required inputs, and user context needed to successfully use the Database Connection Pool Exhaustion Prompt.
You should not use this prompt when you lack direct access to the application's source code or when the relevant pool metrics are unavailable. The analysis depends entirely on the agent's ability to cross-reference observed behavior (e.g., a steadily climbing ActiveConnections count) with implementation details (e.g., a connection acquisition point in a loop). If you only have a database server's perspective without application-level telemetry, the agent cannot trace the leak to its origin in code. Similarly, this prompt is not a substitute for a database administrator's performance tuning of the server itself; it is specifically for diagnosing exhaustion caused by the application client. For high-risk production environments, the output must be treated as a strong hypothesis requiring human validation before any configuration or code change is deployed.
Before using this prompt, assemble a context package: a time-series snapshot of pool metrics, a sample of slow query logs from the saturation window, and the relevant code paths that acquire and release connections. The prompt's effectiveness is directly proportional to the quality of this input. After receiving the AI agent's output, expect a structured report that identifies a primary leak candidate, a secondary long-running transaction pattern, and a recommended pool size with justification. The next step is to have a senior engineer review the agent's code annotations and proposed patch before opening a pull request. Avoid the temptation to blindly apply the pool sizing recommendation without understanding the underlying fix; increasing the pool size without resolving a leak only delays the next exhaustion event.
Use Case Fit
Where the Database Connection Pool Exhaustion Prompt works and where it introduces risk. Use these cards to decide whether this prompt fits your operational context before wiring it into an incident response harness.
Good Fit: Production Pool Saturation Incidents
Use when: on-call engineers receive alerts for connection pool exhaustion (e.g., ConnectionPoolTimeout, TooManyConnections) and need to correlate pool metrics with application code to identify leak sources. Guardrail: Ensure the prompt receives recent pool metrics, query latency data, and relevant source files. The output is a structured leak hypothesis, not a replacement for database admin intervention.
Bad Fit: Network or Infrastructure Outages
Avoid when: the root cause is a network partition, load balancer misconfiguration, or database server crash rather than application-level connection mismanagement. Guardrail: Precede this prompt with a connectivity check. If the database is unreachable, route to infrastructure incident playbooks instead of code-level diagnosis.
Required Inputs: Metrics, Code, and Config
What to watch: Running this prompt without pool metrics, connection lifecycle logs, or the relevant source files produces generic advice that wastes incident time. Guardrail: Validate that pool saturation metrics, query duration percentiles, and the connection-acquiring code paths are available before invoking. Missing inputs should block execution.
Operational Risk: Actionable but Unverified Fixes
What to watch: The prompt may suggest code changes (e.g., adding try-finally blocks, reducing transaction scope) that look correct but introduce new bugs if applied without review. Guardrail: Treat all output as investigation guidance. Require human review and a staging verification step before any suggested patch reaches production.
Variant: Pool Sizing Recommendation Mode
Use when: the incident is resolved and the team needs a postmortem recommendation for pool size, timeout, and queue tuning. Guardrail: Switch to a sizing-focused variant that consumes peak load data, current pool settings, and resource constraints. Do not run sizing recommendations during an active incident—focus on leak identification first.
Tool Dependency: Requires Repository Context Access
What to watch: The prompt depends on access to source code, connection pool configuration files, and recent deployment history. If the AI agent lacks repository access or the codebase is not indexed, output quality degrades sharply. Guardrail: Verify that the agent has read access to the relevant repository and that connection pool configuration is discoverable before invoking.
Copy-Ready Prompt Template
A copy-ready prompt for diagnosing database connection pool exhaustion by correlating pool metrics, query patterns, and application code.
This prompt template is designed to be pasted directly into an AI coding agent with access to your repository, database metrics, and configuration files. It instructs the agent to systematically correlate connection pool saturation signals with application code patterns, identifying leak sources and recommending sizing adjustments. Replace every square-bracket placeholder with real data from your incident context before execution. The prompt assumes the agent has read access to source code, database configuration files, and recent deployment or change logs.
textYou are an SRE investigating a database connection pool exhaustion incident. Your task is to identify the root cause of pool saturation and produce a structured diagnosis with remediation steps. ## Input Data - Pool metrics snapshot: [POOL_METRICS_JSON_OR_TEXT] - Query latency percentiles during incident: [QUERY_LATENCY_DATA] - Connection lifecycle events (acquire, release, timeout): [CONNECTION_LIFECYCLE_LOG] - Application configuration for connection pooling: [POOL_CONFIG_FILE_CONTENTS] - Relevant source code paths to search: [SOURCE_CODE_PATHS] - Recent deployments or configuration changes: [RECENT_CHANGES_LOG] - Database server-side connection count during incident: [DB_SERVER_CONNECTION_COUNT] ## Output Schema Return a JSON object with the following structure: { "diagnosis": { "primary_cause": "leak|long_running_transaction|pool_undersizing|connection_storm|other", "confidence": "high|medium|low", "evidence_summary": "string summarizing key evidence" }, "leak_sources": [ { "file_path": "string", "function_or_block": "string", "leak_mechanism": "unclosed_connection|transaction_not_committed|missing_finally_block|async_leak|other", "code_snippet": "string", "estimated_contribution_percent": number } ], "pool_sizing_recommendation": { "current_max": number, "recommended_max": number, "rationale": "string", "risks_of_change": "string" }, "immediate_mitigations": ["string"], "long_term_fixes": ["string"], "requires_human_review": true_or_false } ## Constraints - Ground every leak source claim in specific code locations found in the repository. Do not speculate without code evidence. - If pool metrics show connections accumulating without release, prioritize leak detection over sizing recommendations. - If query latency is high but pool utilization is low, consider long-running transactions or lock contention as alternative causes. - Cross-reference connection lifecycle events with application code paths that acquire connections. - Flag any code path where connection release is conditional on exception handling without a finally block or equivalent. - If confidence is "low," set requires_human_review to true and explain what additional data would increase confidence. ## Risk Level: [HIGH|MEDIUM|LOW] - If HIGH: Production database availability is at risk. Prioritize immediate mitigations and require human review before applying fixes. - If MEDIUM: Performance degradation is occurring but not yet critical. Balance speed and thoroughness. - If LOW: Early warning signals. Focus on long-term fixes and sizing adjustments. ## Tools Available - Code search across repository: use grep or semantic search to find connection acquisition and release patterns. - Configuration file reading: inspect pool configuration files for max connections, timeout settings, and validation queries. - Log analysis: parse connection lifecycle logs for acquire/release timing and timeout events. ## Examples of Leak Patterns to Detect 1. Connections opened in try blocks without finally-block release. 2. ORM sessions created but not closed after request completion. 3. Async connection pools where acquire is not paired with release in all code paths. 4. Transaction objects committed or rolled back but the underlying connection not returned to pool. 5. Connection pools shared across threads without proper thread-local handling.
After pasting this prompt, verify that the agent has access to all referenced data sources. If the agent cannot access live metrics, provide a snapshot file. If the repository is large, narrow [SOURCE_CODE_PATHS] to the services or modules most likely to manage database connections. For high-risk production incidents, always set requires_human_review to true in the output and validate the agent's code-level findings against your own code review before applying any fixes. Run this prompt in a read-only agent session first to avoid unintended modifications to configuration files.
Prompt Variables
Required inputs for the Database Connection Pool Exhaustion Prompt. Validate each placeholder before execution to prevent hallucinated metrics or source-code mismatches.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[POOL_METRICS] | Current connection pool telemetry: active, idle, pending, max size, wait time, and timeout counts over the incident window | {"active": 48, "idle": 2, "pending": 31, "max": 50, "avg_wait_ms": 4200, "timeout_count": 147} | Schema check: require numeric fields for active, idle, pending, max, avg_wait_ms, timeout_count. Reject if max is zero or missing. Timestamp range must match incident window. |
[QUERY_LATENCY_P95] | 95th percentile query latency in milliseconds during the exhaustion period, broken down by query fingerprint if available | {"overall_p95_ms": 850, "top_fingerprints": [{"fingerprint": "SELECT orders WHERE status", "p95_ms": 3400}]} | Schema check: overall_p95_ms required. Fingerprint array optional but recommended. Reject if latency values are negative or exceed 300000 ms without explicit justification. |
[CONNECTION_LIFECYCLE_LOG] | Sample of application logs showing connection open, close, and error events with timestamps and trace IDs | 2025-03-15T14:23:01.002Z trace-id=abc123 event=connection-acquired 2025-03-15T14:23:01.002Z trace-id=abc123 event=connection-leaked | Parse check: each line must contain timestamp, trace-id, and event field. Event values must be from allowed set: connection-acquired, connection-released, connection-leaked, connection-timeout. Minimum 20 events required for statistical significance. |
[REPOSITORY_CONTEXT] | Paths to source files containing connection pool configuration, query methods, and transaction management code | ["src/db/pool.ts", "src/services/order-service.ts", "src/db/transaction-manager.ts"] | File existence check: verify each path exists in the repository at the analyzed commit. Reject if any path is unresolved. File content must be accessible for correlation with pool metrics. |
[RECENT_DEPLOYS] | List of deployments within 24 hours preceding the exhaustion event, with commit SHAs and change summaries | [{"deployed_at": "2025-03-15T13:45:00Z", "commit": "a1b2c3d", "summary": "Added bulk order processing with extended transaction scope"}] | Schema check: deployed_at must be ISO 8601, commit must be 7-40 hex chars, summary required. Empty array allowed if no recent deploys, but must be explicit. Time window: 24 hours before first exhaustion signal. |
[POOL_CONFIG] | Current connection pool configuration parameters from application config or infrastructure-as-code | {"max_connections": 50, "min_idle": 5, "max_lifetime_ms": 1800000, "connection_timeout_ms": 30000, "leak_detection_threshold_ms": 60000} | Schema check: max_connections, connection_timeout_ms required. All numeric values must be positive. Cross-validate max_connections against [POOL_METRICS].max. Mismatch is a critical finding. |
[INCIDENT_WINDOW] | Start and end timestamps defining the exhaustion incident boundary for analysis | {"start": "2025-03-15T14:20:00Z", "end": "2025-03-15T14:35:00Z"} | Schema check: both fields required, ISO 8601 format, end must be after start. Window duration should be between 1 minute and 4 hours. Reject if window exceeds 4 hours without explicit multi-incident justification. |
Implementation Harness Notes
How to wire the Database Connection Pool Exhaustion Prompt into an incident response or CI/CD pipeline.
This prompt is designed to be called by an automation harness during an active incident or as a scheduled diagnostic check. The harness must gather the required inputs—pool metrics, query latency percentiles, connection lifecycle logs, and relevant application code—before invoking the model. Because the output includes a leak source identification and pool sizing recommendation that could trigger automated remediation, the harness should treat the model's output as a structured hypothesis, not a direct command. The prompt's [OUTPUT_SCHEMA] placeholder expects a JSON contract with fields for leak_source, confidence, evidence, recommended_pool_size, and requires_human_review. Your harness must validate that the model returns valid JSON conforming to this schema before any downstream action is taken.
Wire the prompt into your observability stack by triggering it when connection pool utilization exceeds a defined threshold (e.g., 80% for more than 5 minutes) or when connection timeout errors spike. The harness should assemble the [INPUT] block from your metrics store (Prometheus, Datadog), your APM traces for query latency, and your connection lifecycle logs from the application or pool library (HikariCP, pgBouncer). For the [CONTEXT] placeholder, use a RAG retrieval step that pulls the relevant database interaction code—look for files containing getConnection, DataSource, or ORM session management patterns. This retrieval step is critical because the model needs to correlate pool exhaustion symptoms with specific code patterns like missing finally blocks, unclosed result sets, or transaction boundaries that span non-DB work. Log the full prompt and response to your incident channel for postmortem review.
Add a validation layer after the model responds. Check that leak_source references a specific file path and line number range present in your repository. If confidence is below 0.7, route the output to a human on-call engineer via your incident management tool (PagerDuty, Opsgenie) rather than applying any automated fix. For the pool sizing recommendation, compare the suggested value against your current configuration and flag any change greater than 50% for human approval. Implement a retry with backoff if the model returns malformed JSON or fails to include all required fields; after three retries, escalate to a human. Do not allow the harness to execute ALTER DATABASE or pool configuration changes without explicit human approval, even if the model's confidence is high. The prompt is a diagnostic tool, not a self-healing controller.
Expected Output Contract
Fields, types, and validation rules for the structured diagnosis response. Use this contract to parse and validate the model output before surfacing it in a dashboard or runbook.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
leak_source | object | Must contain 'pattern' (string enum: connection_leak, long_running_transaction, pool_misconfig, client_backpressure, unknown) and 'confidence' (float 0.0-1.0). Confidence below 0.7 must trigger human review flag. | |
leak_source.evidence | array of objects | Each object must have 'file_path' (string matching repo file), 'line_range' (string like 'L45-L52'), and 'snippet' (string). Array must not be empty if pattern is not 'unknown'. | |
leak_source.evidence[].file_path | string | Must match a valid relative path in the repository context provided. Validate with exists-in-repo check. | |
pool_metrics_summary | object | Must contain 'current_active' (integer), 'current_idle' (integer), 'max_pool_size' (integer), 'queue_depth' (integer), and 'avg_wait_ms' (float). All integers must be non-negative. | |
contributing_factors | array of strings | Each string must be one of: missing_close, transaction_no_commit, slow_query_blocking, pool_size_too_small, connection_timeout_misconfig, or upstream_backpressure. Array must not be empty. | |
pool_sizing_recommendation | object | Must contain 'current_max' (integer), 'recommended_max' (integer), 'rationale' (string), and 'risk_of_overprovisioning' (string enum: low, medium, high). recommended_max must be greater than or equal to current_max. | |
remediation_steps | array of objects | Each object must have 'priority' (integer 1-5), 'action' (string), 'file_target' (string or null), and 'verification_query' (string). Array must be sorted by priority ascending. Minimum 1 step. | |
requires_human_review | boolean | Must be true if leak_source.confidence is below 0.7, if contributing_factors includes 'unknown', or if pool_sizing_recommendation.risk_of_overprovisioning is 'high'. Otherwise false. |
Common Failure Modes
When diagnosing database connection pool exhaustion, the prompt often fails silently before producing a wrong answer. These are the most common failure modes and how to guard against them.
Missing Pool Metrics Context
What to watch: The prompt receives only a vague 'connection pool exhausted' error message without active/idle counts, wait queue depth, or connection age histograms. The model hallucinates a leak source from generic patterns rather than actual metrics. Guardrail: Require structured pool metrics as a mandatory input field. If metrics are absent, the prompt must output a MISSING_INPUT classification instead of a diagnosis.
Source Code Grounding Drift
What to watch: The model identifies a connection leak in PaymentService.java but the repository contains no such file, or the referenced line numbers don't match the actual codebase. The diagnosis sounds plausible but is untethered from reality. Guardrail: Require every code reference to include a file path and line range. Add an eval step that verifies referenced files exist in the repository context before accepting the output.
Confusing Correlation with Causation
What to watch: The prompt observes that pool exhaustion coincided with a recent deployment and attributes the incident to that deploy without examining whether the deploy changed connection-handling code. The model treats temporal proximity as causal proof. Guardrail: Add a constraint requiring the prompt to explicitly state whether the suspect code path was modified in the correlated deployment window. If no diff evidence exists, the output must flag the attribution as speculative.
Ignoring Connection Lifecycle Stages
What to watch: The prompt focuses exclusively on 'connections not being closed' and misses other exhaustion causes: slow consumers holding connections too long, connection creation storms from cold starts, or pool max-size misconfiguration relative to workload concurrency. Guardrail: Include a required diagnostic checklist in the prompt that forces the model to evaluate all four exhaustion categories: leaks, long-held connections, burst creation, and sizing misconfiguration before selecting a primary cause.
Pool Sizing Recommendation Without Workload Data
What to watch: The prompt confidently recommends increasing the pool size from 20 to 50 without analyzing concurrent request patterns, database server connection limits, or whether the real problem is slow queries rather than insufficient connections. Guardrail: Require the prompt to output a sizing recommendation only when it has concurrent request counts and database-side connection limits. Otherwise, output a DATA_GAP note and recommend gathering workload data first.
Transaction Boundary Blindness
What to watch: The prompt identifies a method that acquires a connection but fails to recognize that the connection is held across an outer transaction boundary managed by a framework annotation or AOP proxy. The leak source is misattributed to the wrong code layer. Guardrail: Add a prompt instruction to trace connection acquisition through transaction managers, ORM session factories, and connection proxies before declaring a leak location. Require the output to name the transaction propagation level when applicable.
Evaluation Rubric
Criteria for testing the Database Connection Pool Exhaustion Prompt before production deployment. Each row defines a specific quality dimension, a concrete pass standard, a failure signal that triggers a retry or rejection, and a test method that can be automated or run manually.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Source Grounding | Every leak source claim references a specific file path, class, or method name from the repository context | Output contains leak hypotheses without code references or uses vague language like 'somewhere in the codebase' | Parse output for file paths and class names; verify each exists in the provided repository context via grep or AST lookup |
Pool Metric Correlation | Diagnosis explicitly connects observed pool metrics (wait time, active connections, idle count) to the identified leak pattern | Output lists pool metrics but does not link them to the root cause hypothesis or misinterprets metric direction | Check that each metric mentioned in the diagnosis section appears in the input [POOL_METRICS] and is cited in the causal chain |
Leak Classification Accuracy | Leak type is classified into one of the expected categories: unclosed connection, long-running transaction, connection pinning, or misconfigured pool size | Output invents a leak category not supported by evidence or fails to classify the leak type at all | Validate classification label against a closed set; if confidence is low, require a second pass with explicit evidence extraction |
Pool Sizing Recommendation Validity | Recommended pool size falls within a reasonable range based on input [MAX_CONNECTIONS], [CURRENT_POOL_SIZE], and observed wait times | Recommendation exceeds [MAX_CONNECTIONS], suggests zero change without justification, or omits numeric sizing entirely | Assert that recommended size is an integer between 1 and [MAX_CONNECTIONS]; flag if no before/after comparison is provided |
Transaction Duration Analysis | Long-running transaction hypothesis includes specific duration thresholds, query patterns, or transaction boundaries from [QUERY_LATENCY] data | Output claims long-running transactions without citing any duration evidence or query examples | Scan output for time values or duration ranges; confirm they are derived from input data, not hallucinated |
Remediation Actionability | Each remediation step includes a specific code change, configuration adjustment, or monitoring addition that an engineer can execute | Remediation section contains only generic advice like 'check your connection handling' or 'review your code' | Count remediation items; each must contain a verb and a target (file, config key, or monitoring metric). Flag items with fewer than 10 words |
Uncertainty Handling | Output explicitly states confidence level for each finding and flags any hypothesis that requires further investigation | Output presents all findings with equal certainty or makes definitive claims without acknowledging evidence gaps | Search for confidence indicators (high/medium/low, percentage, or explicit caveats). Fail if zero uncertainty markers are present |
Output Schema Compliance | Response strictly follows the [OUTPUT_SCHEMA] with all required fields present and correctly typed | Output is missing required fields, contains extra top-level keys, or uses wrong types (string instead of array, etc.) | Validate output against [OUTPUT_SCHEMA] using JSON Schema validator; reject if validation errors exist |
Enabling Efficiency, Speed & Accuracy
Intelligent Analysis, Decision & Execution
We build AI systems for teams that need search across company data, workflow automation across tools, or AI features inside products and internal software.
Talk to Us
Search across company data
Give teams answers from docs, tickets, runbooks, and product data with sources and permissions.
Useful when people spend too long searching or get different answers from different systems.

Automate internal workflows
Use AI to route work, draft outputs, trigger actions, and keep approvals and logs in place.
Useful when repetitive work moves across multiple tools and teams.

Add AI to products and internal tools
Build assistants, guided actions, or decision support into the software your team or customers already use.
Useful when AI needs to be part of the product, not a separate tool.
Adapt This Prompt
How to adapt\nAdd a strict output schema, require source code correlation, and include pool sizing calculations. Wire the prompt into an incident response harness with retries, schema validation, and logging.\n\n```markdown\nAnalyze the following connection pool state and produce a structured diagnosis.\n\nPool Metrics:\n[POOL_METRICS]\n\nApplication Code:\n[RELEVANT_SOURCE_FILES]\n\nOutput Schema:\n[OUTPUT_SCHEMA]\n\nConstraints:\n- Correlate every leak hypothesis to a specific code location.\n- Calculate recommended pool size with justification.\n- If confidence is below 0.7, flag for human review.\n```\n\n### Watch for\n- Silent format drift when the model omits required schema fields\n- Pool sizing recommendations that ignore application instance count\n- Missing human review flag when confidence is borderline

About the author
Prasad Kumkar
CEO & MD, Inference Systems
Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.
His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.
Partnered with leading AI, data, and software stack.
How We Work
Custom AI workflows for your Business
One-fit-all AI don't work for modern businesses. At Inferensys, we aim to understand your business & custom requirements; which we use to define most efficient agentic workflows, the data, and the tools for your business.
01
Review the use case
We understand the task, the users, and where AI can actually help.
Read more02
Pick the right approach
We define what needs search, automation, or product integration.
Read more03
Build the first useful version
We implement the part that proves the value first.
Read more04
Improve from there
We add the checks and visibility needed to keep it useful.
Read moreThe first call is a practical review of your use case and the right next step.
Talk to Us