This prompt is for performance engineers and SREs who have captured a heap dump from a JVM-based application and need to identify the root cause of a memory leak. It is designed to be used when you have already parsed the heap dump with a tool like Eclipse MAT or jhat and have a report of the top retained objects, their allocation sites, and GC behavior. The prompt instructs the model to act as a forensic performance engineer, correlating the heap profile data with the application's source code to pinpoint leak candidates, trace allocation paths, and propose concrete code fixes. Use this when you need a structured, code-aware analysis that goes beyond raw heap numbers.
Prompt
Memory Leak Investigation Prompt from Heap Dumps

When to Use This Prompt
Understand the job-to-be-done, required inputs, and when this heap dump analysis prompt is the right tool versus when a different approach is needed.
The ideal user has access to three things: a parsed heap report (retained size histograms, dominator trees, or leak suspect reports), the relevant application source code or repository context, and GC log data showing collection frequency and pause patterns. Without all three, the analysis will be incomplete. The prompt expects you to supply [HEAP_DUMP_REPORT] containing class-level retained memory breakdowns and allocation site stacks, [SOURCE_CODE] for the suspect classes and their callers, and [GC_LOG_SUMMARY] with collection counts, pause durations, and heap occupancy trends. If you only have a raw .hprof file without parsing, run Eclipse MAT's leak suspect report first—this prompt is not a replacement for heap dump parsing tools.
Do not use this prompt when the issue is a slow memory leak that hasn't yet produced a significant retained heap, when you lack source code access for the suspect classes, or when the problem is actually a GC tuning issue rather than a leak (excessive allocation rate without retained growth). For GC tuning, use the JVM Garbage Collection Pause Analysis Prompt instead. For cases where the heap dump is from a third-party library you cannot modify, the prompt can still identify the leak path but will be limited to configuration or usage-pattern fixes rather than code changes. Always validate the model's code fix suggestions against your test suite before deploying—memory leak fixes can introduce subtle concurrency or lifecycle bugs if applied without review.
Use Case Fit
Where this prompt works and where it does not. Understanding the operational boundaries prevents misapplication and ensures reliable results.
Good Fit: Structured Heap Analysis
Use when: You have a .hprof or compatible heap dump file, access to the repository source code, and need to identify retained objects, allocation hot spots, and leak candidates. Guardrail: The prompt expects parsed heap data (class histogram, dominator tree, GC roots) as input, not raw binary dumps. Pre-process dumps with jhat, Eclipse MAT, or jcmd before invoking the prompt.
Bad Fit: Live Production Profiling
Avoid when: You need real-time memory pressure diagnosis on a running JVM without taking a heap dump. This prompt works on static snapshots, not live jstat, jmap histograms, or flight recorder streams. Guardrail: Use a separate live-profiling prompt for continuous monitoring. Reserve this prompt for post-hoc investigation of captured dumps.
Required Inputs
Must provide: A parsed heap summary (class histogram with retained sizes), dominator tree output, GC root paths for top retained objects, and relevant source files from the repository. Guardrail: Missing source code grounding turns this into generic heap advice. Always include the allocation-site source files for classes appearing in the top retained set.
Operational Risk: False Leak Attribution
What to watch: The prompt may flag classes with large retained size as leaks when they are legitimate caches, session state, or bounded buffers. Guardrail: Require the prompt to distinguish between unbounded growth patterns and bounded retained memory. Include GC cycle data and allocation rate trends to validate whether retained size is actually growing over time.
Operational Risk: Missing Native Memory
What to watch: Heap dumps only show JVM heap memory. Native memory leaks (direct ByteBuffers, JNI allocations, thread stacks, metaspace) are invisible. Guardrail: The prompt should explicitly state when symptoms suggest off-heap leaks and recommend jcmd VM.native_memory or OS-level process analysis as a follow-up investigation path.
Copy-Ready Prompt Template
A reusable prompt for investigating memory leaks from heap dumps, ready to paste into your AI coding agent after filling in the placeholders.
This template is designed to be copied directly into your AI coding agent or LLM interface. It instructs the model to act as a performance engineer, correlating heap dump analysis with your repository's source code to identify memory leak candidates. The prompt uses square-bracket placeholders for all dynamic inputs—fill these in before execution to ground the analysis in your specific runtime data and codebase.
textYou are a senior performance engineer investigating a memory leak in a production service. Your task is to analyze a heap dump summary and correlate findings with the source code in the repository to identify the most likely leak root causes. ## INPUT DATA ### Heap Dump Summary [HEAP_DUMP_SUMMARY] ### Top Retained Objects (class name, retained heap, instance count) [TOP_RETAINED_OBJECTS] ### GC Log Excerpt (last 5 cycles) [GC_LOG_EXCERPT] ### Allocation Site Hotspots (method, allocated bytes, allocation rate) [ALLOCATION_SITE_HOTSPOTS] ## REPOSITORY CONTEXT ### Source Code for Suspect Classes [SOURCE_CODE_SNIPPETS] ### Recent Commits (last 7 days, touching suspect paths) [RECENT_COMMITS] ### Configuration Files (JVM flags, pool sizes, cache configs) [CONFIGURATION_FILES] ## OUTPUT SCHEMA Return a JSON object with this exact structure: { "leak_candidates": [ { "suspect_class": "fully.qualified.ClassName", "retained_heap_mb": 0, "instance_count": 0, "allocation_path": "method chain from allocation site to leak", "source_file": "path/in/repo/SuspectClass.java", "leak_mechanism": "description of why objects are retained (e.g., unclosed resource, growing collection, static reference, listener leak, thread-local accumulation)", "evidence_from_code": "specific line or pattern in the source that supports this diagnosis", "confidence": "high|medium|low", "fix_recommendation": "concrete code change with before/after example" } ], "gc_analysis": { "pause_trend": "increasing|stable|decreasing", "promotion_failure_rate": 0.0, "old_gen_growth_rate_mb_per_minute": 0.0, "correlation_with_allocation_sites": "explanation linking GC behavior to allocation hotspots" }, "excluded_candidates": [ { "class_name": "fully.qualified.ClassName", "exclusion_reason": "why this class is not a leak despite high retained heap" } ], "investigation_priority": ["ordered", "list", "of", "suspect_classes", "to", "investigate", "first"], "requires_human_review": true } ## CONSTRAINTS - Ground every leak candidate in specific source code evidence from the provided snippets. Do not speculate without code-level support. - Distinguish between legitimate caches, buffers, and session state versus unbounded accumulation. - If GC logs show promotion failures, connect them to specific allocation sites. - Flag any configuration that could mask or exacerbate the leak (e.g., oversized heap, disabled GC logging). - If confidence is low for any candidate, explain what additional data would increase it. - Mark `requires_human_review` as true if any fix involves changing cache eviction policies, connection pool sizes, or JVM flags. ## RISK LEVEL [HIGH|MEDIUM|LOW]
Adaptation guidance: Replace each bracketed placeholder with real data from your heap analysis tool (Eclipse MAT, JProfiler, YourKit, or jcmd output). For [SOURCE_CODE_SNIPPETS], include only the classes that appear in the top retained objects list—do not dump the entire repository. For [RECENT_COMMITS], filter to commits touching memory-sensitive paths (caches, connection pools, listeners, collections). If you lack GC logs, remove the gc_analysis section from the output schema and note the gap in your instructions. For high-risk production incidents, always set requires_human_review to true and route the output to an on-call engineer before applying any fix.
Prompt Variables
Required inputs for the memory leak investigation prompt. Each placeholder must be populated with concrete data before the prompt is sent. Missing or incomplete inputs will degrade analysis quality.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[HEAP_DUMP_PATH] | File path or object store URI to the heap dump file for analysis | s3://dumps/prod-svc-2025-03-15.hprof | Must be a valid path accessible to the analysis tool. Check file extension is .hprof, .phd, or .hprof.gz. Null not allowed. |
[REPOSITORY_CONTEXT] | Source code files, class definitions, or repository map relevant to the suspected leaking service | src/main/java/com/example/cache/SessionCache.java | Must include at least the top 5 classes by retained heap size. Validate that file paths match repository structure. Null not allowed. |
[ALLOCATION_SITE_FILTER] | Optional package or class prefix to narrow analysis scope | com.example.cache. | If provided, must match valid Java package naming. Null allowed for full heap analysis. Validate against repository package structure. |
[GC_LOG_PATH] | Path to garbage collection logs for the same time window as the heap dump | /var/log/app/gc-2025-03-15.log | Must be a valid path. Timestamps in GC logs should overlap with heap dump timestamp. Null allowed if GC logs unavailable. |
[RETAINED_SIZE_THRESHOLD] | Minimum retained heap size in bytes for a class to be flagged as a leak suspect | 10485760 | Must be a positive integer. Default 10MB if not specified. Validate as numeric and non-negative. Null allowed for default behavior. |
[OUTPUT_SCHEMA] | Expected JSON structure for the leak analysis report | See output contract for field definitions | Must be a valid JSON schema or reference to a defined output contract. Validate schema parse succeeds before prompt execution. Null not allowed. |
[RECENT_DEPLOY_WINDOW] | Timeframe of recent deployments to correlate with leak onset | 2025-03-14T18:00:00Z to 2025-03-15T06:00:00Z | Must be ISO 8601 datetime range. Validate start is before end. Null allowed if deployment history unavailable. |
[KNOWN_BASELINE_HEAP] | Expected heap usage under normal load for comparison | Heap baseline: 2.1GB avg over 7 days | If provided, must include numeric value and unit. Used to calculate leak rate. Null allowed if baseline unknown. |
Implementation Harness Notes
How to wire the memory leak investigation prompt into an application or workflow with validation, retries, and human review.
This prompt is designed to be called programmatically as part of a performance investigation pipeline, not as a one-off chat interaction. The typical integration point is a CI/CD post-deployment analysis step, an on-call runbook automation, or a developer CLI tool that accepts a heap dump path and repository context. The harness must supply the heap dump summary, GC log excerpts, allocation site tables, and relevant source code snippets as structured inputs before invoking the model. Because heap analysis involves large data volumes, pre-processing is essential: extract the top retained objects, dominator tree summaries, and allocation hot spots from the heap dump using tooling like Eclipse MAT or jeprof before passing a condensed representation to the prompt.
Input assembly requires three data sources wired together: (1) a heap dump analyzer that produces a structured JSON summary of retained sizes, class histograms, and GC root paths; (2) a source code indexer that retrieves the relevant allocation-site source files from the repository; and (3) a GC log parser that extracts pause durations, collection counts, and heap occupancy trends. The harness should populate [HEAP_SUMMARY], [GC_LOG_EXCERPTS], [ALLOCATION_SITE_TABLE], and [REPOSITORY_CONTEXT] placeholders from these sources. If any input is missing or incomplete, the harness must abort with a clear error rather than sending a degraded prompt. Model choice matters: use a model with strong code reasoning capabilities and a context window large enough to hold the assembled evidence. For production use, prefer a model that supports structured output constraints so the JSON schema in [OUTPUT_SCHEMA] can be enforced at the API level rather than relying solely on prompt instructions.
Validation and retries are critical because false-positive leak identifications can waste engineering hours. After receiving the model response, validate that every suspect class in the output has a corresponding entry in the input heap summary, that allocation paths reference real source files from the repository context, and that fix recommendations are syntactically plausible for the language in use. If validation fails, retry once with an augmented prompt that includes the specific validation errors. If the second attempt also fails, escalate to a human reviewer with the raw model output and validation failure details. Logging should capture the prompt version, input hashes, model response, validation results, and any retry attempts for auditability and prompt improvement over time.
Human review integration is mandatory when the prompt identifies a leak candidate with high confidence or recommends a fix that changes memory-sensitive code paths such as collection sizing, cache eviction policies, or finalizer logic. The harness should route these outputs to a review queue with the full evidence chain: the original heap summary, the model's reasoning, and the proposed code change. For lower-confidence findings or informational GC tuning suggestions, the harness can surface them as non-blocking recommendations in the developer's existing observability dashboard. Do not wire this prompt directly into an automated code-fix pipeline without human approval, because memory management changes can introduce new regressions that only manifest under production load patterns.
Expected Output Contract
Defines the structured output schema, field types, and validation rules for the memory leak investigation prompt. Use this contract to parse and validate model responses before surfacing findings to an engineer or feeding them into an automated remediation pipeline.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
leak_candidates | Array of objects | Must be a non-empty JSON array. Each element must conform to the candidate object schema defined in subsequent rows. | |
leak_candidates[].suspect_class | String (FQCN) | Must match the fully qualified class name pattern (e.g., com.example.MyClass). Validate against repository source tree if available; flag if class not found in codebase. | |
leak_candidates[].retained_heap_percent | Number (float) | Must be a positive float between 0.0 and 100.0. Sum of all candidates' percentages should not exceed 100%. Flag if >50% for a single class as critical. | |
leak_candidates[].allocation_sites | Array of strings | Must contain at least one entry. Each string must match a method signature pattern (ClassName.methodName:lineNumber). Validate line numbers exist in current repository version. | |
leak_candidates[].gc_root_path | String | Must be a non-empty string describing the shortest path from GC roots to the leaking object. Should contain class names separated by '->'. Null or empty string triggers a retry. | |
leak_candidates[].source_code_references | Array of objects | Each object must have 'file_path' (string, must exist in repo), 'line_start' (integer), and 'line_end' (integer). Validate file paths against repository index; flag missing files for human review. | |
leak_candidates[].fix_recommendation | String | Must be a non-empty string with at least 50 characters. Should contain actionable code-level guidance. If recommendation contains 'TODO' or placeholder text, escalate for human review. | |
analysis_metadata | Object | Must contain 'heap_dump_source' (string, non-empty), 'analysis_timestamp' (ISO 8601 string), and 'confidence_score' (float 0.0-1.0). Confidence below 0.6 triggers a low-confidence warning and suggests human verification. |
Common Failure Modes
Memory leak investigation prompts fail in predictable ways when heap dump analysis meets repository context. These cards cover the most common failure modes and how to guard against them before the prompt reaches production.
Hallucinated Class Names and Allocation Paths
What to watch: The model invents class names, method signatures, or allocation paths that sound plausible but don't exist in the repository. This happens when the prompt asks for code-level detail but the model lacks sufficient source context or the heap dump symbols don't match the repo's current state. Guardrail: Require every suspect class and allocation site to be grounded in a specific source file path and line number. Add a validator that checks each referenced class against the repository's symbol index before accepting the output.
Misattribution of Retained Memory to Wrong Root Cause
What to watch: The model identifies a large retained heap object and confidently attributes it to a specific code path, but the actual leak is in a different component that holds a reference to that object. The prompt confuses correlation with causation when analyzing dominator trees. Guardrail: Include an explicit instruction to trace the full reference chain from GC root to retained object, not just the immediate dominator. Require the output to list every intermediate reference with its source location before stating a root cause.
Ignoring Recent Code Changes That Introduced the Leak
What to watch: The prompt analyzes the heap dump in isolation without correlating allocation patterns to recent commits, configuration changes, or dependency updates. The model produces a generic diagnosis that misses the actual trigger. Guardrail: Always supply a git diff or commit log for the relevant timeframe as part of the input context. Add an eval check that verifies the output references at least one specific commit or change when attributing cause.
Overlooking Collection-Based Leaks in Favor of Obvious Singletons
What to watch: The model focuses on large singleton objects or caches because they dominate the heap histogram, but the real leak is a steadily growing collection (HashMap, ArrayList, ConcurrentLinkedQueue) that's harder to spot because individual entries are small. Guardrail: Add a specific instruction to analyze collection size distributions and growth patterns across multiple heap dumps if available. Require the output to include a section on collections with abnormal entry counts relative to expected workload.
GC Root Misidentification from Stripped or Obfuscated Symbols
What to watch: When heap dumps come from production builds with stripped debug symbols, obfuscated code, or framework-generated classes, the model misidentifies GC root types or fails to map runtime objects back to source code. Guardrail: Provide a mapping file or deobfuscation table as part of the context. If unavailable, instruct the model to flag any class or root it cannot confidently map and to use bytecode-level descriptors with explicit uncertainty markers rather than guessing.
Producing Fix Recommendations Without Verifying Side Effects
What to watch: The model suggests a fix—such as adding a WeakReference, clearing a cache, or closing a resource—without analyzing whether that change would break existing functionality, introduce race conditions, or violate API contracts elsewhere in the codebase. Guardrail: Require every fix recommendation to include a dependency impact analysis: list every call site, subclass, or configuration that references the modified code. Add a human-review gate before any fix suggestion is accepted for implementation.
Evaluation Rubric
Use this rubric to test the Memory Leak Investigation Prompt before shipping. Each criterion defines a pass standard, a failure signal, and a concrete test method. Run these checks against a curated set of heap dump scenarios and corresponding repository contexts.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Source Grounding | Every suspect class and allocation path cites a specific source file, class name, or method signature from [REPOSITORY_CONTEXT]. | Output mentions a class or method not present in the provided repository context. | Parse output for code references. Cross-reference each reference against the input [REPOSITORY_CONTEXT] using a string match or AST lookup. |
Leak Candidate Identification | Output correctly identifies the top 1-3 classes by retained heap size as primary suspects, matching a pre-labeled golden dataset. | Output misses a known primary suspect class that dominates retained memory in the golden heap dump. | Compare the list of suspect classes in the output against a golden set of expected suspects for the test heap dump. Require at least 80% recall of top-3 suspects. |
Allocation Path Completeness | For each suspect class, the output provides a full allocation path from a known entry point (e.g., servlet, job, listener) to the leaking collection. | Allocation path is truncated, missing intermediate frames, or starts from an irrelevant GC root. | Validate that the allocation path string contains a sequence of method calls. Check that the root frame matches a known entry-point pattern from [REPOSITORY_CONTEXT]. |
GC Behavior Correlation | Output correlates the suspect allocation pattern with a specific GC log observation (e.g., 'Full GC frequency increased after young gen allocation spike'). | Output makes a generic statement about GC pressure without linking it to a specific metric or log event from [GC_LOG_SUMMARY]. | Check for the presence of a GC metric (e.g., pause time, collection count) and a timestamp or time range in the explanation text. |
Fix Recommendation Actionability | Fix recommendation includes a specific code change suggestion (e.g., 'Use WeakHashMap', 'Evict from cache after TTL') tied to a suspect class. | Fix recommendation is vague (e.g., 'Fix the memory leak') or suggests a JVM flag change without a code-level change. | Classify the fix text using a set of known actionable patterns. A pass requires at least one match to a code-level pattern. |
Output Schema Validity | Output is valid JSON that strictly conforms to [OUTPUT_SCHEMA] with all required fields present and correctly typed. | Output is missing a required field like | Validate the raw output string against the [OUTPUT_SCHEMA] using a JSON schema validator. The test must pass with zero errors. |
Confidence Calibration | When the heap dump evidence is ambiguous, the | Output assigns a high confidence score (>0.9) to an incorrect suspect or a low score (<0.5) to a clear, obvious leak. | Run the prompt on a set of heap dumps with known-difficulty diagnoses. Check that the |
Hallucination Resistance | Output does not invent library versions, internal class names, or configuration values not present in [REPOSITORY_CONTEXT] or [HEAP_DUMP_SUMMARY]. | Output fabricates a specific framework version or a configuration file path that does not exist in the provided inputs. | Use a fuzzy string match of all proper nouns in the output against the full text of the inputs. Any unmatched proper noun is a failure signal requiring manual review. |
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
Start with the base prompt and a single heap dump file. Remove strict output schema requirements initially—ask for a free-text analysis first to validate the model understands heap structure. Use a frontier model (GPT-4o, Claude 3.5 Sonnet) with a large context window to ingest the full .hprof summary without chunking.
Add this preamble for exploration:
codeYou are analyzing a Java heap dump. First, summarize the top 10 classes by retained memory. Then identify any objects with suspiciously high instance counts or retained size relative to expected application patterns. Do not suggest code fixes yet—only report what you observe.
Watch for
- Model hallucinating class names or allocation paths not present in the dump
- Misinterpreting GC root reachability when the dump is truncated
- Overly broad "increase heap size" recommendations without evidence
- Confusing retained vs. shallow heap sizes in summary statistics

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