This prompt is designed for performance engineers and AI SREs who are responding to an active latency alert and have access to structured trace data from the spike window. The job-to-be-done is isolating the bottleneck across model inference, tool calls, retrieval, and context assembly spans. Instead of manually scanning individual traces in an observability dashboard, you feed a batch of normalized traces into this prompt to receive a latency attribution breakdown, a ranked list of suspect spans, and the specific timing evidence that supports each hypothesis. The prompt assumes traces are already collected, normalized, and contain span-level timing data—it does not query your observability backend or perform real-time data extraction.
Prompt
Latency Spike Root-Cause Trace Prompt

When to Use This Prompt
Use this prompt to accelerate root-cause analysis of a production latency spike by structuring diagnostic reasoning across dozens of traces into a ranked suspect list backed by per-span timing evidence.
Do not use this prompt when you lack structured trace data, when the spike is still ongoing and traces are incomplete, or when the root cause is already known to be an infrastructure outage (e.g., a dead model endpoint or a network partition). This prompt is also not a replacement for your observability dashboard or alerting system; it is a diagnostic accelerator for the phase of an incident where you have trace data in hand and need to move from 'latency is high' to 'the retrieval step in the vector store is adding 800ms of p99 latency due to a cold cache.' For ambiguous cases where multiple spans show correlated degradation, the prompt's ranked suspect list helps prioritize your next investigation step rather than delivering a single definitive answer. Always validate the output against raw trace data before taking remediation actions such as rolling back a prompt version, scaling a service, or adjusting a timeout.
After using this prompt, you should have a clear, evidence-backed hypothesis about which component is the primary latency contributor. The next step is to validate that hypothesis against additional traces from the spike window and, if confirmed, to execute the appropriate remediation—whether that means tuning retrieval parameters, adjusting model routing, or escalating to the infrastructure team. If the prompt's output is inconclusive or the top suspect has low confidence, expand the input batch to include more traces or narrow the time window to isolate the spike's onset more precisely.
Use Case Fit
Where this prompt works and where it does not. Use these cards to decide if the Latency Spike Root-Cause Trace Prompt is the right tool for your current incident.
Good Fit: Structured Trace Data Available
Use when: you have a batch of production traces from the spike window with consistent span attributes (model inference, tool calls, retrieval, context assembly). Guardrail: validate that trace spans include timing fields before running the prompt; missing or null timing data will produce unreliable attributions.
Bad Fit: Unknown or Multi-Cause Incidents
Avoid when: the latency spike has no clear temporal boundary or spans multiple independent incidents. Guardrail: use the Multi-Trace Failure Pattern Detection Prompt first to cluster traces before isolating latency-specific root causes.
Required Inputs: Timing-Annotated Spans
What to watch: the prompt requires per-span latency data (duration, start time, end time) for model inference, tool calls, retrieval, and context assembly. Guardrail: pre-process traces to extract and normalize span timing fields; reject traces with missing or negative durations before analysis.
Operational Risk: Spurious Correlation
What to watch: the prompt may attribute latency to a span that is correlated with but not causally responsible for the spike (e.g., a tool call that waited on a slow upstream dependency). Guardrail: cross-reference the ranked suspect list with infrastructure metrics (CPU, memory, network) and require human review for single-source attributions.
Operational Risk: Incomplete Trace Coverage
What to watch: if only a subset of requests are traced, the prompt may miss the true bottleneck that affects untraced requests. Guardrail: confirm trace sampling coverage before analysis; flag results with a confidence caveat when coverage is below 95% of spike-window traffic.
Operational Risk: Prompt Drift After Model Updates
What to watch: a model update may change how the prompt interprets span names or timing fields, producing inconsistent attributions across versions. Guardrail: pin the model version during incident response and re-validate the prompt's output schema against a known trace before relying on results.
Copy-Ready Prompt Template
Paste this prompt into your incident analysis workflow. Replace square-bracket placeholders with your trace data and baseline values.
This prompt template is designed to be dropped directly into your observability or incident response tooling. It expects structured trace data from the latency spike window and a set of baseline traces for comparison. The model's job is to attribute added latency to specific spans—model inference, tool calls, retrieval, context assembly—and produce a ranked suspect list with per-span timing evidence. The output is a structured latency attribution breakdown that your engineering team can act on immediately.
textYou are an AI performance engineer analyzing a latency spike incident. Your task is to compare traces from the spike window against baseline traces and attribute the added latency to specific spans. ## INPUT DATA ### Spike Window Traces [SPIKE_TRACES] ### Baseline Traces (pre-spike, same or similar request types) [BASELINE_TRACES] ### Spike Window Time Range [SPIKE_WINDOW_START] to [SPIKE_WINDOW_END] ### Latency Threshold for Alert [LATENCY_THRESHOLD_MS] ## OUTPUT SCHEMA Return a JSON object with this exact structure: { "summary": { "spike_window": "string", "total_traces_analyzed": number, "traces_exceeding_threshold": number, "mean_latency_increase_ms": number, "p95_latency_increase_ms": number }, "span_attribution": [ { "span_type": "model_inference | tool_call | retrieval | context_assembly | other", "mean_added_latency_ms": number, "p95_added_latency_ms": number, "percentage_of_total_increase": number, "affected_trace_count": number, "evidence_trace_ids": ["string"], "observations": "string" } ], "ranked_suspects": [ { "rank": number, "span_type": "string", "specific_target": "string (e.g., 'tool:vector_search', 'model:gpt-4-turbo', 'retrieval:pinecone_query')", "confidence": "high | medium | low", "evidence_summary": "string", "recommended_action": "string" } ], "anomalies": [ { "trace_id": "string", "anomaly_type": "string", "description": "string", "severity": "critical | high | medium | low" } ], "needs_human_review": boolean, "human_review_reason": "string (if applicable)" } ## CONSTRAINTS 1. Only attribute latency to spans present in the trace data. Do not speculate about spans not captured. 2. If a span type shows no statistically significant increase, set its values to 0 and note it in observations. 3. For each suspect, cite at least one specific trace ID as evidence. 4. If the spike window contains fewer than [MIN_TRACES_FOR_CONFIDENCE] traces, set confidence to "low" for all suspects and set needs_human_review to true. 5. Distinguish between latency caused by the span itself vs. latency caused by queuing or contention before the span started. 6. Flag any trace where the root cause appears to be external to the AI system (network timeout, upstream dependency failure) in the anomalies array. 7. If tool-call latency increased but the tool response payload size also increased, note this correlation rather than assuming a tool degradation. ## ANALYSIS STEPS 1. Compute per-span latency deltas between spike and baseline traces. 2. Group spans by type and compute aggregate statistics. 3. Rank span types by contribution to total latency increase. 4. Within each high-contribution span type, identify the specific target (model name, tool name, retrieval index). 5. Check for correlated changes: did context size grow? Did tool response payloads increase? Did model change? 6. Flag any outlier traces that don't fit the dominant pattern. 7. Assess whether the evidence is sufficient for high-confidence attribution or requires human review. Return only the JSON object. No markdown fences, no additional commentary.
To adapt this template, replace the square-bracket placeholders with your actual data. [SPIKE_TRACES] and [BASELINE_TRACES] should contain structured trace objects with at minimum: trace_id, span_type, span_name, duration_ms, start_time, and any relevant metadata like model name or tool endpoint. [MIN_TRACES_FOR_CONFIDENCE] should be set based on your traffic volume—typically 10–20 traces for a meaningful comparison. If your observability platform exports traces in OpenTelemetry format, pre-process them into the span-level structure this prompt expects before injection. The output schema is designed to be machine-readable for downstream automation: pipe the ranked suspects into your incident channel, use the needs_human_review flag to gate automated escalation, and store the full attribution breakdown in your incident document for postmortem use.
Prompt Variables
Inputs the Latency Spike Root-Cause Trace Prompt needs to produce a reliable attribution breakdown. Validate each input before running the prompt to avoid garbage-in-garbage-out diagnosis.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[TRACE_LIST] | Array of trace objects from the spike window, each containing span-level timing data, service names, and operation names. | JSON array of OpenTelemetry-format traces with startTime, endTime, and span.metadata.latency_ms fields. | Schema check: array length > 0. Each trace must have a traceId and at least one span with duration. Reject if spans are missing timestamps. |
[BASELINE_LATENCY_P50] | Median latency for the same operation during a healthy window, used to calculate excess latency per span. | 145ms | Must be a positive number. Compare against [BASELINE_WINDOW_START] and [BASELINE_WINDOW_END] to ensure the baseline window does not overlap with the spike window. Null allowed if no baseline exists; prompt will flag this. |
[SPIKE_WINDOW_START] | Start of the incident window for trace filtering, in ISO 8601 format. | 2025-03-15T14:03:00Z | Parse check: valid ISO 8601. Must be before [SPIKE_WINDOW_END]. Timezone required. Reject if the window is wider than 1 hour without explicit override. |
[SPIKE_WINDOW_END] | End of the incident window for trace filtering, in ISO 8601 format. | 2025-03-15T14:11:00Z | Parse check: valid ISO 8601. Must be after [SPIKE_WINDOW_START]. Duration should be short enough to isolate the spike (recommended < 15 min). |
[SERVICE_MAP] | Mapping of span service names to human-readable component labels for the attribution report. | {"vector-store-prod": "Vector DB", "llm-gateway": "Model Inference"} | Schema check: valid JSON object. Keys must match serviceName values in [TRACE_LIST] spans. Missing mappings will cause unlabeled components in output. |
[LATENCY_THRESHOLD_MS] | Minimum excess latency in milliseconds required to flag a span as a suspect contributor. | 50 | Must be a positive integer. Set too low and noise dominates; set too high and real contributors are missed. Recommend 2x the p95 jitter of the healthy baseline. |
[MAX_SUSPECTS] | Maximum number of suspect components to include in the ranked output list. | 5 | Must be an integer between 1 and 10. Controls output verbosity. If more components exceed [LATENCY_THRESHOLD_MS], the prompt will truncate and note omitted suspects. |
Implementation Harness Notes
How to wire the Latency Spike Root-Cause Trace Prompt into an automated incident response workflow with validation, retries, and human review gates.
This prompt is designed to be called programmatically as part of an incident response runbook, not as a one-off chat interaction. The harness should fetch traces from your observability platform (e.g., Datadog, Grafana, Honeycomb) for the spike window, format them into the [TRACE_DATA] placeholder, and invoke the model via your production API. The prompt expects raw span data with timing fields—if your trace exporter omits duration_ms or start_time, preprocess the spans to compute these before injection. Run this prompt only after you have isolated the time window and service boundaries; feeding it unfiltered firehose data will produce noisy, low-confidence attributions.
Validation and output contract: Parse the model's JSON output against a strict schema before acting on it. The latency_attribution array must contain objects with span_name, component, p50_ms, p99_ms, delta_from_baseline_ms, and evidence_span_ids. Reject any response where evidence_span_ids reference spans not present in the input trace data—this is a hallucination signal. Implement a retry loop with a maximum of 2 attempts, appending the validation error to the retry prompt as [PREVIOUS_ERROR]. If the model fails to produce valid JSON after 2 retries, escalate to a human responder with the raw trace data and the partial output. Model choice: Use a model with strong JSON mode and long-context handling (e.g., GPT-4o, Claude 3.5 Sonnet) because trace payloads can exceed 50k tokens during spike windows. Set temperature=0 to maximize reproducibility of the attribution breakdown.
Logging and audit trail: Log every invocation—input trace count, spike window parameters, model response, validation result, and final attribution—to your incident management system (e.g., PagerDuty, FireHydrant, or a dedicated audit table). This creates an evidence trail for postmortems and allows you to compare attributions across incidents over time. Human review gate: If the ranked_suspects list includes a component marked as [RISK_LEVEL] = high (e.g., the primary database connection pool or the model inference endpoint), require a human to acknowledge the finding before automated remediation fires. This prevents a misattribution from triggering a rollback or scale-up on the wrong component. Next step: After the harness returns a validated attribution, feed the top suspect into your remediation runbook—whether that means scaling a service, rolling back a model version, or failing over to a secondary region—and attach the prompt's output as the justification artifact.
Expected Output Contract
Defines the exact fields, types, and validation rules for the latency spike root-cause trace analysis response. Use this contract to parse, validate, and store the model output before surfacing it in dashboards or incident reports.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
attribution_breakdown | Array of objects | Must contain at least one span entry. Each object must include span_name, latency_added_ms, and evidence_trace_ids. | |
attribution_breakdown[].span_name | String | Must match a known span category: model_inference, tool_call, retrieval, context_assembly, or other. Enum check required. | |
attribution_breakdown[].latency_added_ms | Number (integer) | Must be a positive integer. Sum of all latency_added_ms values must not exceed total_spike_latency_ms by more than 10%. | |
attribution_breakdown[].evidence_trace_ids | Array of strings | Each trace ID must match the pattern [TRACE_ID_PATTERN]. Array must not be empty. At least one ID must appear in the input trace set. | |
ranked_suspects | Array of objects | Must contain 1-5 entries sorted by confidence_score descending. Each object must include suspect_component, confidence_score, and supporting_evidence. | |
ranked_suspects[].suspect_component | String | Must reference a specific component: an API endpoint, model version, tool name, or infrastructure resource. Generic labels like 'the model' are invalid. | |
ranked_suspects[].confidence_score | Number (float 0.0-1.0) | Must be between 0.0 and 1.0 inclusive. Scores must be monotonically non-increasing in the array. Null not allowed. | |
analysis_summary | String | Must be 1-3 sentences. Cannot be empty. Must include the primary bottleneck span name and the top-ranked suspect component. |
Common Failure Modes
Latency spike root-cause analysis is a high-stakes diagnostic task. The prompt must reason over structured trace spans, resist hallucinating correlations, and produce a verifiable attribution breakdown. These are the most common failure modes and how to guard against them.
Spurious Correlation with Unrelated Spans
What to watch: The model attributes latency to a span that is merely temporally coincident, not causally responsible. For example, blaming a retrieval call that happened to complete just before a slow inference step. Guardrail: Require the prompt to cite per-span duration evidence and compare it against baseline latency for that span type. Include a causal_confidence field in the output schema and flag correlations below a threshold for human review.
Ignoring Cumulative Micro-Delays
What to watch: The model focuses on a single large span and misses death-by-a-thousand-cuts scenarios where many small, serialized tool calls or context assembly steps add up to a significant spike. Guardrail: Instruct the prompt to compute a cumulative latency sum for repeated span types and compare it against the top single-span contributor. Require a cumulative_impact_ranking in the output.
Hallucinated Span Attributes or Missing Data
What to watch: The model invents span details, such as a model name or token count, that are not present in the input trace data, or it confidently analyzes a span that was truncated from the input. Guardrail: Add a strict instruction: 'Only reference span IDs, durations, and attributes explicitly present in the provided trace. If data is missing for a span, mark it as insufficient_data and exclude it from the suspect list.'
Confusing Queue Time with Processing Time
What to watch: The model conflates time spent waiting in a queue or for a lock with active processing time, leading to incorrect attribution to the processing service rather than upstream backpressure. Guardrail: Require the prompt to separate queue_duration from execution_duration for each span. The output schema should have distinct fields for these metrics, and the analysis must prioritize spans with high execution duration for processing bottlenecks.
Overfitting to the First Anomalous Span
What to watch: The model identifies the first span that exceeds a baseline and declares it the root cause, failing to trace the bottleneck further upstream to a dependency or a context-window expansion that caused the slowdown. Guardrail: Use a chain-of-thought instruction: 'Trace the latency from the user-facing entry point backward through the dependency graph. Identify the most upstream span with anomalous duration before attributing blame to downstream effects.'
Ignoring External Dependency Timeouts
What to watch: The model treats a timeout as a simple long-duration span, missing the fact that a retry loop or a fallback mechanism was triggered, which is the true multiplier of the latency spike. Guardrail: Instruct the prompt to explicitly check for error or timeout status flags on spans. If a timeout is detected, the analysis must calculate the total cost including retries and fallback execution, not just the initial failed call.
Evaluation Rubric
Criteria for testing the latency attribution output before relying on it in production incident response. Each criterion targets a specific failure mode common in trace analysis prompts.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Span Attribution Completeness | All spans in the spike window are assigned to a latency category (model inference, tool call, retrieval, context assembly, other) with a timing delta in milliseconds | Output contains spans marked 'unknown' or missing timing deltas; total attributed latency does not sum to within 5% of the spike window duration | Parse output JSON and validate that sum of per-span deltas equals total spike latency within tolerance; check for null or missing category fields |
Bottleneck Identification Accuracy | The top-ranked suspect span accounts for at least 40% of the total latency delta and is supported by per-span timing evidence from the trace | Top suspect is a tie across three or more spans with no clear majority; bottleneck explanation references spans not present in the input trace | Inject a known bottleneck trace (e.g., retrieval span consuming 70% of added latency) and verify the output ranks it first with correct evidence |
Evidence Grounding | Every latency attribution claim includes a specific span ID, operation name, and measured duration from the input trace | Output contains phrases like 'likely caused by' or 'probably due to' without a span ID reference; timing values appear rounded or estimated rather than extracted | Grep output for span IDs from the input trace; flag any attribution sentence that lacks a span ID or contains speculative language without trace evidence |
Ranked Suspect List Ordering | Suspects are ordered by latency contribution descending; each suspect includes a span identifier, latency delta, percentage of total spike, and a one-line explanation | Suspect list is unordered or sorted alphabetically; percentage values exceed 100% when summed; explanations are generic and not trace-specific | Parse the suspect list array and validate descending order by latency delta; confirm each entry has all four required fields; check that percentages sum to 100% ± 2% |
Spike Window Boundary Adherence | Analysis is confined to spans within the provided spike window start and end timestamps; no spans outside the window are included in the attribution | Output references spans from before or after the spike window; baseline comparison uses spans from a different time range than specified | Provide a trace with a clearly bounded spike window and a span just outside it; verify the output excludes the out-of-window span from attribution |
Baseline Comparison Validity | Baseline latency values are drawn from the provided baseline window or pre-spike period; delta calculations use baseline minus spike, not absolute values | Baseline values appear to be hardcoded defaults (e.g., 100ms for all operations) rather than extracted from the input; delta direction is inverted | Supply a trace with a known baseline window; verify output baseline values match the provided data; check that latency deltas are positive when spike exceeds baseline |
Output Schema Compliance | Output is valid JSON matching the specified schema with all required fields present and no extra top-level keys | Output is markdown-wrapped JSON, plain text, or missing required fields like 'bottleneck_span_id' or 'suspect_list'; contains hallucinated fields not in the schema | Validate output against the JSON schema using a programmatic validator; reject any response that fails schema parsing or contains undefined fields |
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 small set of traces from the spike window. Remove strict output schema requirements initially—focus on getting the model to correctly identify spans and attribute latency. Use a lightweight markdown table output instead of full JSON.
codeAnalyze these traces from a latency spike window [START_TIME] to [END_TIME]. For each trace, list the spans and their durations. Identify which span type (model inference, tool call, retrieval, context assembly) contributed the most latency. Output as a simple table.
Watch for
- Model confusing wall-clock time with span duration
- Missing span-type classification when spans are nested
- Overly broad attribution that blames the longest span without analyzing whether it's expected

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