Inferensys

Prompt

Database Connection Pool Exhaustion Analysis Prompt

A practical prompt playbook for using Database Connection Pool Exhaustion Analysis Prompt in production AI workflows.
Developer doing prompt engineering on laptop, prompt variations visible on screen, casual coding session.
PROMPT PLAYBOOK

When to Use This Prompt

Defines the precise diagnostic scenario, required inputs, and boundaries for the connection pool exhaustion analysis prompt.

This prompt is designed for backend engineers and SREs who are actively responding to an application outage where the immediate symptom is database connection pool exhaustion. The ideal user has already identified the symptom—typically through APM dashboards or monitoring alerts showing Timeout waiting for idle object, Active connections: [MAX], or a flatline in application throughput—but has not yet isolated the root cause. The prompt's job is to accelerate the transition from symptom to root cause by analyzing raw connection pool logs, relevant application stack traces, and database performance metrics to distinguish a slow connection leak from a legitimate traffic spike or a sudden blocking operation.

To use this prompt effectively, you must provide structured, timestamped data from three sources: the connection pool logs showing connection acquisition/release events and timeouts, application traces or thread dumps that reveal what the code was doing while holding connections, and database metrics such as active queries, locks, and transaction duration. The prompt is not a replacement for your APM or connection pool monitoring dashboard. It is a force multiplier when those tools have surfaced the symptom but the root cause remains ambiguous. Do not use this prompt for proactive capacity planning, general performance tuning, or as a substitute for setting proper connection pool sizes and timeouts in your application configuration.

Before executing this prompt, ensure you have isolated the time window of the incident and gathered the relevant logs. The prompt will produce a structured analysis identifying the specific query or code path leaking connections, the blocking operation preventing connection return, and a short-term mitigation. However, the output is a diagnostic hypothesis, not a guaranteed fix. Always validate the identified code path against your source code and consider the long-term fix separately. If the data is incomplete or the incident is ongoing, prioritize restoring service with a pool size increase or connection timeout reduction before running a full analysis.

PRACTICAL GUARDRAILS

Use Case Fit

Where the Database Connection Pool Exhaustion Analysis Prompt works, where it fails, and what you must have in place before relying on it.

01

Good Fit: Leaked Connection Diagnosis

Use when: application logs show ConnectionPoolExhausted or timeout errors after periods of normal load. The prompt excels at correlating acquisition stack traces with transaction boundaries to identify code paths that open connections without closing them. Guardrail: Provide the full connection acquisition stack trace and the surrounding application code context; the model cannot trace what it cannot see.

02

Bad Fit: Network or Infrastructure Outages

Avoid when: the root cause is a network partition, load balancer misconfiguration, or database server crash. The prompt analyzes application-side connection behavior, not infrastructure telemetry. Feeding it network error logs will produce plausible but incorrect connection-leak hypotheses. Guardrail: Pre-filter logs to confirm the database server is reachable and accepting connections before invoking this prompt.

03

Required Inputs

Must have: connection pool metrics (active, idle, pending, max size), timestamps of exhaustion events, and application stack traces at the point of connection acquisition. Nice to have: transaction duration histograms and recent deployment markers. Guardrail: If stack traces are missing, the prompt must return an abstention with a list of missing evidence, not a guess. Build this into the harness as a required validation gate.

04

Operational Risk: False Attribution to Traffic Spikes

Risk: The model may attribute exhaustion to a legitimate traffic spike when the real cause is a slow query holding connections open under normal load. This misclassification delays the correct fix. Guardrail: Always cross-reference the prompt's output with transaction duration data. If p95 latency increased before the exhaustion event, override the traffic-spike hypothesis and investigate blocking operations first.

05

Operational Risk: Hallucinated Code Paths

Risk: When stack traces are truncated or ambiguous, the model may invent specific method names or line numbers that do not exist in the codebase. Acting on hallucinated locations wastes engineering time. Guardrail: The eval harness must verify that every code location in the output matches a real symbol in the provided source context. Flag any location not present in the input as a hallucination failure.

06

Operational Risk: Confusing Slow Consumers with Leaks

Risk: A query that takes 30 seconds under degraded database performance will hold a connection for 30 seconds, mimicking a leak. The prompt may incorrectly flag the query pattern as a leak rather than a performance degradation. Guardrail: Include database-side query performance metrics (e.g., pg_stat_activity wait events) in the input context. The prompt must differentiate between 'connection held too long due to slow execution' and 'connection never returned to pool.'

PROMPT PLAYBOOK

Copy-Ready Prompt Template

Paste this prompt into your AI harness to analyze connection pool exhaustion. Replace the square-bracket placeholders with incident-specific data.

This template is designed to be the core analytical engine for diagnosing database connection pool exhaustion. It forces the model to differentiate between a legitimate traffic spike and a connection leak by requiring evidence from logs, pool metrics, and application traces. The output is structured to deliver an immediate mitigation step and a root cause hypothesis, not a generic troubleshooting guide. Before using this prompt, ensure you have gathered the relevant data sources; the model's analysis is only as good as the input context.

text
You are an SRE specializing in database performance and backend failure analysis. Your task is to diagnose a database connection pool exhaustion event.

## INPUT DATA
- **Pool Metrics:** [POOL_METRICS]
- **Application Logs (anonymized):** [APP_LOGS]
- **Relevant Code Context (connection lifecycle):** [CODE_CONTEXT]
- **Deployment/Config Change Timeline:** [CHANGE_TIMELINE]

## ANALYSIS INSTRUCTIONS
1.  **Triage:** First, determine if the exhaustion is from a legitimate traffic spike or a connection leak. A leak is indicated by a growing number of active connections without a proportional increase in request rate, or connections stuck in an 'idle in transaction' state.
2.  **Identify the Leak:** If a leak is suspected, pinpoint the specific code path or query pattern. Look for connections acquired but not released in `finally` blocks, or long-running transactions that hold connections without activity.
3.  **Identify the Blocker:** If a spike is suspected, identify the slowest queries or blocking operations that are preventing connections from being recycled quickly.
4.  **Propose Mitigation:** Provide an immediate, short-term mitigation (e.g., a query kill command, a feature flag to disable a non-critical path, a temporary pool size increase with a caveat).
5.  **Propose Root Cause Fix:** Provide a long-term code or configuration fix.

## OUTPUT FORMAT
You must respond with a valid JSON object and nothing else. Do not include markdown fences.
{
  "exhaustion_type": "LEAK" | "TRAFFIC_SPIKE" | "INCONCLUSIVE",
  "confidence": "HIGH" | "MEDIUM" | "LOW",
  "evidence": [
    {
      "source": "pool_metrics | app_logs | code_context",
      "observation": "string",
      "interpretation": "string"
    }
  ],
  "leaking_code_path_or_blocking_query": "string | null",
  "immediate_mitigation": {
    "action": "string",
    "command_or_config": "string | null",
    "risk": "string"
  },
  "root_cause_fix": {
    "description": "string",
    "code_change_suggestion": "string | null",
    "configuration_change": "string | null"
  },
  "requires_human_review": true
}

## CONSTRAINTS
- Never suggest a permanent fix that simply increases the pool size without addressing the underlying leak or bottleneck.
- If the evidence is insufficient to determine the cause, set `exhaustion_type` to `INCONCLUSIVE` and `confidence` to `LOW`. Do not guess.
- The `immediate_mitigation.risk` field must honestly describe the potential side effects (e.g., 'may drop in-flight requests', 'increases database memory pressure').

To adapt this template, replace the [PLACEHOLDER] variables with raw data from your observability stack. For [POOL_METRICS], paste a snapshot of your connection pool dashboard showing active, idle, and pending connections. For [APP_LOGS], include log lines surrounding the timeout errors, ensuring any PII is redacted. The [CODE_CONTEXT] should be the specific functions where connections are acquired and released. After running the prompt, validate the JSON output against a schema validator in your harness. If requires_human_review is true or confidence is LOW, route the analysis to an on-call engineer instead of automatically applying the mitigation.

IMPLEMENTATION TABLE

Prompt Variables

Required inputs for the Database Connection Pool Exhaustion Analysis Prompt. Each placeholder must be populated with structured data for the prompt to produce a reliable root cause hypothesis.

PlaceholderPurposeExampleValidation Notes

[CONNECTION_POOL_METRICS]

Time-series data showing active, idle, pending, and max connections for the target pool during the incident window

{"timestamp": "2025-01-15T14:32:00Z", "active": 98, "idle": 2, "pending": 47, "max": 100}

Validate that timestamps are sequential, values are non-negative integers, and max > 0. Reject if active + idle exceeds max by more than 5% without explanation.

[APPLICATION_TRACE_SAMPLE]

Representative distributed trace spans showing the full lifecycle of slow or failed requests during pool exhaustion

{"trace_id": "abc123", "spans": [{"service": "api", "operation": "getUser", "duration_ms": 32000, "status": "timeout"}]}

Must contain at least one span with duration exceeding the connection timeout threshold. Validate span parent-child relationships are consistent. Reject empty trace arrays.

[QUERY_LOG_SAMPLE]

Database query log entries for connections held during the exhaustion period, including query text and duration

{"query": "SELECT * FROM users WHERE id = ?", "duration_ms": 28500, "connection_id": 42, "state": "active"}

Validate that connection_id values map to the pool metrics source. Query text must be non-empty. Duration must be a positive number. Flag queries exceeding [SLOW_QUERY_THRESHOLD_MS].

[DEPLOYMENT_TIMELINE]

List of recent deployments, config changes, or feature flags toggled within the lookback window before the incident

[{"event": "deploy v2.4.1", "timestamp": "2025-01-15T14:20:00Z", "component": "user-service"}]

Timestamps must be within [LOOKBACK_WINDOW_HOURS] of the incident start. Empty array is allowed but must be explicitly noted in the output as missing correlation data.

[POOL_CONFIGURATION]

Current connection pool settings including max size, timeout values, leak detection thresholds, and validation query

{"max_pool_size": 100, "connection_timeout_ms": 30000, "idle_timeout_ms": 600000, "leak_detection_threshold_ms": 0}

Validate that max_pool_size matches the value in [CONNECTION_POOL_METRICS]. connection_timeout_ms must be a positive integer. If leak_detection_threshold_ms is 0, note that leak detection is disabled.

[INCIDENT_WINDOW]

Start and end timestamps defining the incident period for analysis

{"start": "2025-01-15T14:30:00Z", "end": "2025-01-15T14:45:00Z"}

Validate that start precedes end and the window duration is between 1 minute and 24 hours. All other time-series inputs must overlap this window by at least 80%.

[EXPECTED_BASELINE_METRICS]

Normal operating metrics for the same pool during a comparable non-incident window for deviation analysis

{"avg_active_connections": 35, "avg_pending_requests": 2, "p99_query_duration_ms": 200, "window": "2025-01-15T13:00:00Z/2025-01-15T13:15:00Z"}

Validate that the baseline window does not overlap with [INCIDENT_WINDOW]. If unavailable, set to null and the prompt must explicitly note that deviation analysis is limited to absolute thresholds only.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the Database Connection Pool Exhaustion Analysis Prompt into an application or operational workflow.

This prompt is designed to be integrated into an automated incident response or debugging pipeline, not just used as a one-off chat. The primary integration point is a webhook or event-driven function that triggers when a connection pool exhaustion alert fires (e.g., from Datadog, Prometheus, or PagerDuty). The harness must gather the required inputs—the raw connection pool logs, application traces for the affected time window, and the pool configuration—and assemble them into the [INPUT] placeholder. A pre-processing step should sanitize any sensitive data like full connection strings or user PII before the prompt is assembled, using a redaction library or regex patterns to replace them with placeholders like [REDACTED_HOST].

The application layer should wrap the LLM call in a retry loop with exponential backoff, catching ValidationError exceptions from the output parser. The model's response must be parsed into a strict JSON schema that includes fields for leak_source (the specific query or code path), blocking_operation, evidence, mitigation_steps, and a confidence_score (0.0 to 1.0). If the JSON is malformed or missing required fields, a repair prompt should be invoked once before failing over to a human on-call engineer. Log every raw prompt, raw response, and parsed output to an immutable audit log for post-incident review. For model choice, a fast, instruction-following model like GPT-4o or Claude 3.5 Sonnet is appropriate; avoid smaller models that may hallucinate code paths under the pressure of complex log data.

The most critical failure mode to guard against is the model confusing a legitimate traffic spike with a connection leak. To mitigate this, the harness should inject a [CONSTRAINTS] block that forces the model to explicitly compare the connection acquisition rate to the request rate. If they are proportional, the model must output a leak_source of null and a confidence_score below a configurable threshold (e.g., 0.6), which the harness should interpret as a signal to suppress the automated diagnosis and escalate to a human. Do not allow the system to automatically execute the model's suggested mitigation steps, such as restarting a connection pool or killing a query, without explicit human approval. The output should be routed to a Slack channel or incident ticket as a structured diagnostic aid, not an autonomous action.

IMPLEMENTATION TABLE

Expected Output Contract

Defines the required structure, types, and validation rules for the analysis output. Use this contract to parse and validate the model's response before surfacing it in a dashboard or routing it to an on-call engineer.

Field or ElementType or FormatRequiredValidation Rule

root_cause_hypothesis

string

Must be a non-empty string. Must not exceed 500 characters. Must explicitly reference a specific query pattern, code path, or configuration value identified in the [LOG_CONTEXT].

leak_type

enum

Must be one of: 'connection_leak', 'slow_query_blocking', 'pool_size_misconfiguration', 'traffic_spike', 'unknown'. If 'unknown', the confidence_score must be <= 0.5.

confidence_score

float

Must be a number between 0.0 and 1.0. If the score is below 0.7, the output must include a non-empty evidence_gaps list.

affected_pool

string

Must match a pool name present in the [LOG_CONTEXT] or be 'global'. Regex validation: ^[a-zA-Z0-9_-]+$.

blocking_operation

object

Required if leak_type is 'slow_query_blocking' or 'connection_leak'. Must contain 'query_fingerprint' (string) and 'avg_duration_ms' (integer). 'query_fingerprint' must not contain raw parameter values.

evidence

array of objects

Must contain at least 1 and no more than 5 items. Each object must have 'source' (string, a log line ID or timestamp from [LOG_CONTEXT]) and 'rationale' (string, max 200 chars). 'source' must be a valid reference found in the input.

short_term_mitigation

string

Must be a single, executable action (e.g., 'KILL QUERY <id>', 'SCALE UP POOL <name>', 'ROLLBACK DEPLOY <id>'). Must not be a generic suggestion like 'optimize queries'.

requires_human_review

boolean

Must be 'true' if confidence_score < 0.9 or leak_type is 'unknown'. Otherwise, can be 'false'.

PRACTICAL GUARDRAILS

Common Failure Modes

Connection pool exhaustion prompts fail in predictable ways. These are the most common failure modes, why they happen, and how to guard against them before the prompt reaches production.

01

Misclassifying Traffic Spikes as Leaks

What to watch: The prompt attributes high connection counts to a leak when the root cause is a legitimate traffic surge or a slow downstream dependency. The model sees high utilization and jumps to the most common pattern without checking request rate metrics. Guardrail: Require the prompt to compare connection count trends against request rate trends. If both rise proportionally, flag as 'possible traffic spike' before labeling as a leak. Include a traffic_correlation_check field in the output schema.

02

Hallucinating Code Paths Without Evidence

What to watch: The model invents a specific function name, file path, or line of code as the leak source when the logs only contain pool metrics and query text. This creates false confidence and sends developers on wild goose chases. Guardrail: Constrain the output to only reference code locations when stack traces or application logs explicitly include them. Add a source_grounding field that states whether the code path came from evidence or is inferred. If inferred, require an explicit confidence: low marker.

03

Ignoring Connection Pool Configuration Limits

What to watch: The prompt diagnoses a leak when the actual problem is a misconfigured pool size that is too small for normal workload. The model focuses on query behavior and misses the configuration context entirely. Guardrail: Always include pool configuration parameters (max_connections, pool_timeout, idle_timeout) as required inputs. Instruct the model to check whether exhaustion occurs at the configured limit before diagnosing a leak. Add a config_check step in the reasoning chain.

04

Confusing Long-Running Queries with Leaked Connections

What to watch: The prompt flags connections held open by slow analytical queries or uncommitted transactions as leaked connections. The connections are legitimately in use but blocking others. Guardrail: Require the prompt to differentiate between 'connection held too long' and 'connection never returned to pool.' Use connection duration thresholds and transaction state (idle in transaction vs active) as distinguishing signals. Output separate categories for each failure mode.

05

Missing the Transaction Boundary Leak Pattern

What to watch: The prompt fails to detect connections stuck in idle in transaction state because it only looks at total connection counts. This is the most common real-world leak pattern and the prompt misses it entirely. Guardrail: Explicitly instruct the prompt to check for connections in idle in transaction state and flag them as high-priority leak candidates. Include a dedicated transaction_state_analysis section in the output that reports counts by connection state.

06

Proposing Unsafe Remediation Without Guardrails

What to watch: The prompt suggests aggressive remediation like 'kill all connections' or 'restart the pool' without warning about in-flight transaction impact or data loss risk. Guardrail: Add a remediation_safety constraint that requires every remediation suggestion to include a risk assessment. For destructive actions, require explicit human approval language. Never allow the prompt to recommend pg_terminate_backend or pool reset without a warning about active transactions.

IMPLEMENTATION TABLE

Evaluation Rubric

Use this rubric to test the prompt's output quality before integrating it into a production triage harness. Each criterion targets a specific failure mode common in connection pool exhaustion analysis.

CriterionPass StandardFailure SignalTest Method

Leak vs. Spike Differentiation

Correctly classifies the root cause as a connection leak, legitimate traffic spike, or misconfiguration based on the provided metrics and logs.

Misclassifies a slow query under normal load as a connection leak, or attributes a leak to a generic 'high traffic' cause without evidence.

Run against a golden dataset of 10 cases: 4 leaks, 4 spikes, 2 misconfigurations. Require >= 90% classification accuracy.

Offending Code Path Identification

Pinpoints the specific query, function, or service method responsible for acquiring and not releasing connections, citing log evidence.

Returns a vague module name (e.g., 'the checkout service') without a specific query or code path, or blames the database driver itself.

Validate that the output contains a specific function name or SQL query hash that matches the injected fault in a synthetic trace.

Blocking Operation Detection

Identifies the specific blocking operation (e.g., an external API call, a long-running transaction) that holds connections open.

Fails to identify a blocking operation when one is present in the trace, or hallucinates a blocking call that does not exist in the provided spans.

Use a trace with an injected 30s external HTTP call inside a transaction. Check if the output names that specific call and its duration.

Mitigation Actionability

Proposes a short-term mitigation that is specific, executable, and directly addresses the diagnosed root cause (e.g., 'add a 5s timeout to X', 'roll back PR #Y').

Suggests only generic advice like 'increase the pool size' or 'optimize queries' without linking it to the specific finding.

Human expert review: 3 SREs independently rate the mitigation as 'actionable and correct' on a 3-point scale. Require a median score of 3.

Evidence Grounding

Every diagnostic claim in the output is supported by a direct reference to a log line, metric value, or span attribute provided in the input.

Makes a confident assertion about a connection count or query latency that contradicts the provided input data, or invents a metric not present.

Automated check: extract all numeric claims from the output and verify each one exists in the structured input data with a tolerance of +/- 5%.

Abstention on Insufficient Data

Outputs a clear 'insufficient data' conclusion with specific missing information listed (e.g., 'need connection pool metrics at 14:03 UTC') when input is incomplete.

Generates a confident but incorrect diagnosis when given only a generic error message with no pool metrics or application traces.

Provide an input containing only 'ERROR: Connection is not available' with no other context. The output must not name a specific code path.

Confidence Calibration

Includes a calibrated confidence level (High/Medium/Low) that accurately reflects the strength of the evidence and the ambiguity of the scenario.

Assigns 'High' confidence to a diagnosis based on a single ambiguous log line, or 'Low' confidence to a clear-cut leak with a smoking-gun stack trace.

Run 20 test cases with known difficulty. Measure Expected Calibration Error (ECE) between stated confidence and actual accuracy. Require ECE < 0.15.

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Use the base prompt with a raw connection pool log dump and minimal output constraints. Focus on getting a readable hypothesis, not a validated one. Accept free-text output with a loose structure.

Prompt modification

Remove strict [OUTPUT_SCHEMA] requirements. Replace with: "Explain what you think is happening and why." Drop the requirement for exact timestamps and pool metric fields.

Watch for

  • Hallucinated query patterns when the log is sparse
  • Confusing a legitimate traffic spike with a connection leak
  • Missing the distinction between wait_time and active_connections
Prasad Kumkar

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.