This prompt is designed for infrastructure engineers, SREs, and FinOps teams who need to perform a surgical root-cause analysis on a single production trace where end-to-end latency exceeded a defined threshold. The job-to-be-done is isolating the specific span—whether it's a retrieval call, model inference, tool execution, or network hop—that is responsible for the latency spike. It requires a raw trace as input, complete with timestamps and span metadata, and produces a structured latency attribution report that decomposes the total latency into per-step measurements. The ideal user is someone who has already identified an anomalous session through monitoring dashboards and now needs to understand exactly what happened inside that session before deciding on a fix.
Prompt
Latency Spike Root-Cause Analysis Prompt

When to Use This Prompt
Understand the specific job this prompt performs and when it is the right tool for diagnosing a single anomalous trace.
This prompt is not a replacement for aggregate observability tools or real-time alerting systems. Do not use it to analyze trends across thousands of traces, to calculate p95 latency across a fleet, or to trigger automated alerts. It is purpose-built for deep, single-session investigation. The prompt assumes you have already isolated a trace of interest—perhaps flagged by a user complaint, a cost anomaly, or a spike on a latency histogram—and you need to explain the spike before escalating to the model provider, adjusting a timeout, or rewriting a tool. The required context includes the raw trace data, a defined latency threshold that was breached, and optionally a baseline percentile for comparison. Without a specific trace to analyze, this prompt will produce a generic report that lacks diagnostic value.
Before using this prompt, confirm that the trace data is complete and includes parent-child span relationships, start and end timestamps, and operation names. If your observability pipeline samples traces or drops spans, the analysis will be incomplete and may misattribute the latency spike. After running the analysis, use the output to decide your next action: if a retrieval span is the culprit, investigate the vector database or embedding service; if model inference is slow, check for token limits, model version changes, or provider throttling; if a tool call is the bottleneck, review the tool's timeout and retry logic. Avoid using this prompt when the latency spike is caused by client-side network conditions or browser rendering, as those factors are typically invisible in server-side traces.
Use Case Fit
Where the Latency Spike Root-Cause Analysis Prompt works and where it introduces risk. Use these cards to decide if this prompt fits your operational context before wiring it into a production harness.
Good Fit: Single-Trace Deep Dive
Use when: You have a single, complete trace with span-level timing data and need to identify which component caused a latency spike. Guardrail: Ensure the trace includes retrieval, model inference, tool-call, and network spans with millisecond-resolution timestamps before invoking analysis.
Bad Fit: Aggregate Trend Analysis
Avoid when: You need to analyze latency trends across thousands of traces or detect gradual drift. This prompt is designed for isolated root-cause analysis, not statistical pattern detection. Guardrail: Use a separate aggregation pipeline for trend analysis and reserve this prompt for drilling into specific high-latency exemplars identified by your monitoring dashboards.
Required Inputs: Span Data Completeness
Risk: Incomplete or missing span data leads to incorrect attribution, such as blaming the model when a network timeout was the real culprit. Guardrail: Validate that the trace payload includes all required span types before running the prompt. Implement a pre-check that rejects traces missing retrieval, inference, or tool-call segments and flags them for manual review.
Operational Risk: Baseline Drift
Risk: Comparing a spike against stale baseline percentiles produces false positives, causing teams to investigate normal variance as if it were an incident. Guardrail: Always pair this prompt with a harness that fetches the most recent baseline from your observability store. If the baseline is older than your configured threshold, the prompt should warn that attribution confidence is reduced.
Operational Risk: Cost Attribution Blindness
Risk: The prompt focuses on latency but may overlook cost spikes caused by expensive model calls or excessive token consumption during the same trace. Guardrail: Extend the harness to include a parallel cost-attribution check. If the latency spike correlates with a cost anomaly, the output should flag both dimensions for the FinOps reviewer.
Process Fit: Incident Response Workflow
Use when: An on-call engineer needs a structured latency attribution report during an active incident to decide whether to escalate to a specific team. Guardrail: Integrate the prompt output into your incident channel with a clear owner tag. The report should conclude with a recommended escalation path so the responder can act immediately rather than re-analyzing the findings.
Copy-Ready Prompt Template
A ready-to-use prompt template for isolating the root cause of a latency spike within a single production trace.
This prompt template is designed to be pasted directly into your investigation notebook or an automated diagnosis harness. It instructs the model to act as an SRE performing a structured latency breakdown on a single trace. The goal is to move from 'the trace was slow' to a precise attribution, identifying whether the spike originated in retrieval, model inference, a specific tool call, or network transit. The output is a structured latency attribution report that can be compared against your service's baseline percentiles.
textYou are an SRE specializing in AI system performance. Analyze the provided trace data to identify the root cause of a latency spike. ## Input Data - Trace JSON: [TRACE_JSON] - Baseline Latency Percentiles (p50, p95, p99) for each span type: [BASELINE_PERCENTILES] ## Analysis Steps 1. Parse the trace into a chronological list of spans. For each span, extract the `span_id`, `operation_name`, `start_time`, and `duration_ms`. 2. Categorize each span into one of the following types: `retrieval`, `model_inference`, `tool_call`, `network`, `other`. 3. For each span, calculate its deviation from the provided p95 baseline for its type. Flag any span where `duration_ms > p95_baseline`. 4. Identify the single span with the highest positive deviation from its p95 baseline. This is the primary latency contributor. 5. Trace the causal chain backward from the primary contributor to the initial user request to identify any upstream triggers (e.g., a large retrieved context causing a slow tool call). ## Output Format You must respond with a valid JSON object conforming to this schema: { "trace_id": "string", "total_duration_ms": number, "primary_latency_contributor": { "span_id": "string", "operation_name": "string", "span_type": "string", "duration_ms": number, "p95_baseline_ms": number, "deviation_from_baseline_ms": number, "upstream_trigger": "string or null" }, "span_breakdown": [ { "span_id": "string", "operation_name": "string", "span_type": "string", "duration_ms": number, "p95_baseline_ms": number, "deviation_from_baseline_ms": number, "is_flagged": boolean } ], "root_cause_hypothesis": "A concise, evidence-based explanation of why the primary contributor was slow." } ## Constraints - Do not invent data. If a baseline is missing for a span type, set `p95_baseline_ms` to null and `deviation_from_baseline_ms` to null. - If multiple spans have similar high deviations, select the one with the largest absolute duration as the primary contributor. - The `root_cause_hypothesis` must reference specific evidence from the trace (e.g., 'The high latency in the tool_call span is directly correlated with a 3x increase in input token size from the preceding retrieval span.').
To adapt this template, replace the [TRACE_JSON] placeholder with the raw span data from your observability platform, such as LangSmith, Arize, or a custom trace store. The [BASELINE_PERCENTILES] placeholder should be populated with your service's established performance baselines. If you lack formal baselines, you can initially use a recent healthy trace's span durations as a rough proxy, but be explicit about this in your harness. For automated use, the JSON output schema is the contract your harness should validate against. If the model fails to return valid JSON or the primary_latency_contributor is missing, implement a retry with a stricter prompt or fall back to a rule-based analysis of the raw spans.
Prompt Variables
Each placeholder required by the Latency Spike Root-Cause Analysis Prompt, its purpose, a concrete example, and how to validate it before execution to prevent misattribution or hallucinated latency data.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[TRACE_JSON] | The full production trace object containing spans, timestamps, and metadata for a single session. | { "trace_id": "abc123", "spans": [ { "span_id": "1", "operation": "model_inference", "start_time": "2025-01-01T00:00:00Z", "duration_ms": 4500 } ] } | Schema check: must parse as valid JSON. Required fields: trace_id (string), spans (array). Each span must have span_id, operation, start_time, and duration_ms. Reject if empty or missing spans. |
[BASELINE_PERCENTILES] | A map of operation names to their p50, p95, and p99 latency values in milliseconds from a healthy baseline window. | { "model_inference": { "p50": 1200, "p95": 2500, "p99": 4000 }, "retrieval": { "p50": 80, "p95": 200, "p99": 500 } } | Schema check: must be a JSON object where each key is a string matching span operations and each value is an object with numeric p50, p95, p99 fields. All values must be positive numbers. Reject if baseline is older than 7 days or derived from a known incident window. |
[LATENCY_THRESHOLD_MS] | The absolute latency threshold in milliseconds above which a span is considered a spike candidate, regardless of baseline. | 5000 | Type check: must be a positive integer. Range check: should be set above the p99 of the slowest baseline operation to avoid false positives. Default to 5000 if not provided. Log a warning if threshold is below the p95 of any baseline operation. |
[OUTPUT_SCHEMA] | The expected JSON schema for the latency attribution report, defining the structure of the output. | { "type": "object", "properties": { "attributions": { "type": "array", "items": { "type": "object", "properties": { "span_id": { "type": "string" }, "operation": { "type": "string" }, "duration_ms": { "type": "number" }, "baseline_p95_ms": { "type": "number" }, "excess_ms": { "type": "number" }, "root_cause_candidate": { "type": "boolean" } }, "required": ["span_id", "operation", "duration_ms", "baseline_p95_ms", "excess_ms", "root_cause_candidate"] } } }, "required": ["attributions"] } | Schema check: must be a valid JSON Schema object. Must include required fields for each attribution. Validate that the output conforms to this schema after generation. If the model output fails schema validation, retry with the schema injected into the prompt constraints. |
[CONSTRAINTS] | Additional natural-language rules for the analysis, such as ignoring specific span types or requiring a minimum excess percentage for root-cause candidacy. | Ignore spans with operation 'heartbeat'. Only flag a span as a root-cause candidate if its excess_ms exceeds 50% of its baseline p95. | Parse check: must be a non-empty string. Inject verbatim into the system prompt. If constraints reference span operations, validate that those operations exist in the baseline percentiles map. Log a warning if a constraint references an operation not present in the trace. |
[MAX_ATTRIBUTIONS] | The maximum number of spans to include in the attribution report, preventing output bloat for traces with many spans. | 10 | Type check: must be a positive integer between 1 and 50. Default to 10. If the trace has fewer spans than this value, output all spans. If more, select the top N by excess_ms. Validate that the output attribution array length does not exceed this value. |
[MODEL_ID] | Identifier for the model generating the analysis, used for logging and cost attribution in the harness. | gpt-4o-2024-08-06 | Format check: must be a non-empty string matching a known model identifier in your routing config. Validate against an allowlist of deployed model IDs before execution. Reject if the model ID is not recognized or is deprecated. |
Implementation Harness Notes
How to wire the latency spike root-cause analysis prompt into an investigation workflow.
This prompt is designed to be the first step in a latency investigation, not a standalone report. It should be wired into an observability pipeline where a single trace, already flagged by a p99 latency alert, is fed into the model along with its baseline percentile data. The prompt expects a pre-processed trace object containing per-span timing, so your harness must first extract spans from your tracing backend (e.g., LangSmith, Arize, Datadog, or custom OpenTelemetry collectors) and format them into the [TRACE_SPANS] placeholder. The baseline percentiles in [BASELINE_PERCENTILES] should be computed from a rolling window of healthy traffic—do not hardcode them or use global averages, as that will produce false attributions during low-traffic periods.
The implementation should include a validation layer that checks the model's output against the expected [OUTPUT_SCHEMA] before the report reaches an engineer. At minimum, validate that the attribution array sums to 100% (±1% tolerance), that every span ID referenced in the report exists in the input trace, and that the dominant_span field points to a real span. If validation fails, retry once with the same prompt and a prepended error message describing the schema violation. If the retry also fails, log the raw trace and model output to a human review queue rather than silently dropping the investigation. For high-severity incidents where latency directly impacts an SLO, route the validated report to an on-call channel with a link to the full trace.
Model choice matters here. Use a model with strong structured output support and a large enough context window to hold the full trace JSON plus baseline data. GPT-4o, Claude 3.5 Sonnet, and Gemini 1.5 Pro are all suitable. Avoid small or quantized models for this task—they frequently miscalculate percentage attributions or hallucinate span IDs. If you must use a smaller model, add a post-processing step that recalculates the latency percentages from the raw span durations in the input trace and only uses the model's output for the textual root-cause hypothesis and recommendations. This hybrid approach keeps the numerical analysis trustworthy while still getting the narrative value from the LLM.
Finally, store every analysis result alongside the trace ID and prompt version in your observability database. This creates an audit trail for post-incident review and lets you measure whether the prompt's attributions align with the actual remediation actions taken by engineers. Over time, you can use this data to fine-tune the baseline percentile windows, adjust the prompt's emphasis on specific span types, or build a few-shot example set from confirmed root causes that improves accuracy on recurring failure patterns.
Expected Output Contract
The exact JSON structure the prompt must return. Use this contract to validate the model's output before it enters your incident response or cost-analysis pipeline.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
trace_id | string | Must match the [TRACE_ID] input exactly. Fail if missing or mismatched. | |
analysis_timestamp | ISO 8601 string | Must parse as a valid UTC datetime. Fail if unparseable or in the future. | |
spans | array of objects | Must be a non-empty array. Fail if null, empty, or not an array. | |
spans[].span_name | string | Must be one of the predefined span types: retrieval, llm_inference, tool_call, network, other. Fail on unrecognized values. | |
spans[].duration_ms | number | Must be a positive number. Fail if negative, zero, or non-numeric. Sum of all span durations must not exceed total_latency_ms by more than 5%. | |
spans[].baseline_p95_ms | number or null | Must be a positive number or null if no baseline exists. Fail if negative. If null, the root_cause span must not be this span unless all baselines are null. | |
root_cause_span | string | Must exactly match one span_name in the spans array. Fail if the identified span's duration_ms is less than its baseline_p95_ms when a baseline exists. | |
total_latency_ms | number | Must be a positive number. Fail if negative or zero. Must be greater than or equal to the sum of all span durations. |
Common Failure Modes
Latency spike root-cause analysis fails in predictable ways. These are the most common failure modes when diagnosing a single trace, along with concrete guardrails to prevent misattribution.
Misattributing Network Latency to Model Inference
What to watch: The prompt blames the model for a slow response when the trace shows high time-to-first-byte but low tokens-per-second. The root cause is often a network hop, load balancer queue, or cold start, not inference speed. Guardrail: Require the prompt to separate time-to-first-byte from inter-token latency and compare each span against baseline percentiles before attributing blame.
Ignoring Client-Side and Pre-Request Latency
What to watch: The trace starts at the API gateway, missing client-side delays, DNS resolution, or authentication overhead. The analysis incorrectly attributes end-to-end latency to server-side components. Guardrail: Include a pre-request span check in the harness. If client-side spans are absent, flag the trace as incomplete and refuse to draw conclusions about total latency.
Overlooking Context Window Assembly Costs
What to watch: Retrieval and prompt assembly spans are aggregated into a single step, hiding the fact that packing 50 chunks into a 100K context window consumed 2 seconds. The prompt misattributes this to retrieval speed. Guardrail: Require the prompt to break down the context assembly phase into retrieval, re-ranking, and tokenization sub-spans. Flag any trace where these are collapsed.
Comparing Against Stale or Wrong Baselines
What to watch: The prompt compares current latency against a p50 baseline when the workload is bursty, or uses a baseline from a different model version. This produces a false spike or masks a real regression. Guardrail: The harness must validate that baseline percentiles match the same model version, region, and workload profile. Reject comparisons where the baseline is older than the deployment window.
Tool-Call Serialization Masking Parallelization Opportunities
What to watch: The trace shows sequential tool calls that could have been parallelized, inflating total latency. The prompt attributes the spike to tool execution speed rather than poor orchestration. Guardrail: Include a dependency analysis step. The prompt must identify independent tool calls and flag them when they are executed sequentially, recommending parallelization as a mitigation.
Token-Level Cost Attribution Without Context Window Accounting
What to watch: The prompt calculates cost based only on output tokens, ignoring that a bloated system prompt or excessive retrieved context drove up input token costs and latency. Guardrail: The harness must itemize input tokens by source—system prompt, user message, retrieved context, tool results—and flag any source exceeding a configurable budget threshold before attributing cost.
Evaluation Rubric
Criteria for testing the quality of a latency attribution report before deploying this prompt into an incident response workflow. Each criterion should be validated against a set of known traces with injected latency spikes.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Span identification completeness | All spans from the input trace are present in the output report with correct operation names | Missing spans or spans with incorrect operation names in the output | Compare span count and operation names in output against input trace; require 100% match |
Latency attribution accuracy | The span identified as the root cause matches the injected latency spike in the test trace | Root cause span differs from the injected spike location or multiple spans incorrectly flagged | Run against 10 traces with known injected spikes; require correct identification in 9/10 cases |
Baseline comparison validity | Baseline percentile values are correctly calculated from the provided baseline dataset and compared to the spike trace | Baseline values are fabricated, use wrong percentile, or comparison uses absolute instead of percentile deviation | Pre-compute expected baseline values; assert output matches within 1ms tolerance |
Per-step breakdown granularity | Each span includes latency, percentage of total request time, and deviation from baseline in milliseconds and percentage | Missing latency fields, incorrect percentage calculations, or deviation expressed only in absolute terms | Parse output JSON; validate all required fields present and percentage calculations sum to 100% ± 1% |
Root cause justification quality | Root cause explanation cites specific evidence from the trace (span name, duration, baseline deviation) without hallucination | Explanation contains unsupported claims, references spans not in the trace, or uses vague language without metrics | Manual review of 5 outputs; require specific metric citations and zero hallucinated span references |
Confidence score calibration | Confidence score reflects actual diagnostic certainty: high when spike is isolated to one span, low when multiple spans deviate | Confidence is always high regardless of ambiguity or confidence contradicts the evidence presented | Test with mixed-certainty traces; assert confidence ≥ 0.8 for clear single-span spikes and ≤ 0.6 for multi-span deviations |
Output schema compliance | Output strictly matches the defined [OUTPUT_SCHEMA] with all required fields, correct types, and no extra fields | Missing required fields, incorrect types (string instead of number), or additional unlisted fields present | Validate output against JSON Schema; require zero validation errors |
Actionability of recommendations | Recommendations are specific to the identified bottleneck (e.g., 'reduce retrieved chunks from 20 to 10' for retrieval spike) and executable | Generic recommendations like 'optimize performance' or recommendations for spans not identified as bottlenecks | Review 5 outputs; require at least one specific, span-targeted recommendation per report |
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 trace dump. Remove the strict output schema and percentile comparison logic. Ask the model for a plain-text latency breakdown first.
codeAnalyze this trace and list each span with its duration. Identify the slowest step and suggest one likely cause. Trace: [TRACE_JSON]
Watch for
- Model inventing span names or durations not present in the trace
- Missing distinction between wall-clock time and model inference time
- No baseline comparison, so "slow" is subjective

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