Use this prompt when you need to attribute end-to-end latency in a RAG pipeline to specific retrieval substeps—embedding generation, vector search, reranking, and context assembly—separate from model inference time. This is essential for infrastructure engineers and RAG developers who suspect that retrieval, not generation, is the dominant latency contributor but lack a structured breakdown to prove it. The prompt expects a production trace span that includes timestamps for each retrieval substep alongside the final generation span. Without per-step timing data, the prompt cannot produce a meaningful breakdown, so verify that your observability instrumentation captures these substeps before using this playbook.
Prompt
Latency Contribution by Retrieval Step Prompt

When to Use This Prompt
Define when to isolate retrieval latency from generation latency in RAG traces and when a simpler approach is sufficient.
The prompt produces a latency attribution table with absolute and percentage contributions for each retrieval substep, a comparison against the generation latency, and anomaly flags when any substep exceeds a configurable threshold. You must provide the trace data in a structured format, including span names, start and end timestamps, and any metadata about the retrieval configuration (e.g., embedding model, index type, reranker). The output is designed to be consumed by a monitoring dashboard or incident report, not as a conversational summary. Wire the prompt into an automated trace analysis pipeline where traces exceeding an end-to-end latency budget trigger this breakdown automatically, rather than running it ad-hoc on every request.
Do not use this prompt when the trace lacks substep granularity, when the retrieval pipeline is a single opaque API call, or when you only need a coarse binary answer about whether retrieval is slow. In those cases, a simpler per-step latency comparison prompt is more appropriate. Also avoid this prompt when the generation step dominates latency and retrieval optimization is not the immediate priority—running it on every slow trace without filtering wastes token budget. If the trace includes tool calls or multi-model routing, use the broader per-step latency breakdown prompt instead, as this prompt is specialized for retrieval-only pipelines. After identifying the bottleneck substep, follow up with targeted optimization work on that component—embedding model selection, index tuning, reranker latency reduction, or context assembly refactoring—rather than treating the breakdown as the final deliverable.
Use Case Fit
Where this prompt works and where it does not.
Good Fit: RAG Pipeline Tuning
Use when: you have instrumented traces with discrete retrieval spans (embedding, vector search, reranking, context assembly) and need to isolate which step dominates end-to-end latency. Guardrail: confirm your tracing system captures sub-span timestamps before running this prompt; missing spans produce misleading attribution.
Bad Fit: Black-Box API Calls
Avoid when: your retrieval is a single opaque API call with no internal span breakdown. The prompt cannot attribute latency to steps it cannot see. Guardrail: instrument the retrieval pipeline with OpenTelemetry or equivalent span-level tracing before using this prompt.
Required Inputs
What you need: trace data containing per-step start/end timestamps for embedding generation, vector search execution, reranking, and context assembly. Guardrail: validate that timestamps are in a consistent timezone and monotonic before feeding traces to the prompt; clock skew between services produces negative latency values.
Operational Risk: Missing Reranking Step
What to watch: if your pipeline sometimes skips reranking, the prompt may attribute latency incorrectly or produce incomplete breakdowns. Guardrail: include a conditional step in your harness that checks for reranking span presence and flags traces where it is absent before running the latency attribution prompt.
Operational Risk: Context Assembly Overlap
What to watch: context assembly time may overlap with generation token processing in streaming setups, inflating perceived retrieval latency. Guardrail: use span parent-child relationships, not just sequential timestamps, to separate overlapping work. The prompt should receive span-tree metadata, not flat timelines.
Scale Limit: High-Cardinality Traces
What to watch: running this prompt on thousands of traces individually is expensive and slow. Guardrail: pre-aggregate traces by retrieval configuration version and sample representative traces per configuration. Use the prompt on the sample set, not the full population.
Copy-Ready Prompt Template
A reusable prompt template for isolating retrieval latency from generation latency in RAG traces.
This section provides a copy-ready prompt template you can drop into your observability tooling, internal debugging notebook, or automated trace analysis pipeline. The prompt is designed to accept a structured trace span from a RAG pipeline and produce a latency attribution breakdown that separates retrieval work (embedding generation, vector search, reranking, context assembly) from model inference time. Use this template when you have end-to-end trace data and need to determine whether retrieval or generation is the dominant latency contributor before making infrastructure or configuration changes.
textYou are a performance analysis assistant specialized in RAG pipeline latency diagnosis. Your task is to analyze a production trace span and produce a latency attribution breakdown that isolates retrieval steps from generation steps. ## INPUT You will receive a structured trace object containing span timestamps, durations, and metadata for a single RAG request. The trace includes the following fields: [TRACE_JSON] ## TASK 1. Parse the trace spans and identify each distinct step in the request lifecycle. 2. Classify each step into one of the following categories: - EMBEDDING_GENERATION: Time spent creating embeddings for the query or documents. - VECTOR_SEARCH: Time spent executing the vector similarity search. - RERANKING: Time spent reranking retrieved candidates. - CONTEXT_ASSEMBLY: Time spent formatting, truncating, or assembling retrieved context for the prompt. - MODEL_INFERENCE: Time spent waiting for the LLM to generate tokens. - OVERHEAD: Any remaining time not attributable to the above categories (network, serialization, queue wait). 3. Calculate the total duration and percentage contribution for each category. 4. Flag any step that exceeds its expected latency threshold. Use the following default thresholds unless overridden: - EMBEDDING_GENERATION: [EMBEDDING_THRESHOLD_MS] - VECTOR_SEARCH: [VECTOR_SEARCH_THRESHOLD_MS] - RERANKING: [RERANKING_THRESHOLD_MS] - CONTEXT_ASSEMBLY: [CONTEXT_ASSEMBLY_THRESHOLD_MS] - MODEL_INFERENCE: [INFERENCE_THRESHOLD_MS] 5. If the trace contains multiple retrieval calls (e.g., hybrid search), break down retrieval latency by each retrieval sub-step. ## OUTPUT SCHEMA Return a JSON object with the following structure: { "trace_id": "string", "total_duration_ms": number, "breakdown": [ { "category": "EMBEDDING_GENERATION | VECTOR_SEARCH | RERANKING | CONTEXT_ASSEMBLY | MODEL_INFERENCE | OVERHEAD", "duration_ms": number, "percentage": number, "sub_steps": [ { "step_name": "string", "duration_ms": number, "threshold_exceeded": boolean, "threshold_ms": number } ] } ], "anomalies": [ { "step_name": "string", "observed_ms": number, "expected_ms": number, "severity": "LOW | MEDIUM | HIGH", "hypothesis": "string" } ], "retrieval_total_ms": number, "generation_total_ms": number, "retrieval_percentage": number, "generation_percentage": number } ## CONSTRAINTS - Do not invent durations or steps not present in the trace. - If a step's duration cannot be determined from the trace data, mark it as "UNKNOWN" and exclude it from percentage calculations. - If the trace contains nested or overlapping spans, resolve parent-child relationships before calculating totals to avoid double-counting. - Flag anomalies only when the observed duration exceeds the threshold by 50% or more. - If no thresholds are provided, use the trace's own p50 durations from [BASELINE_TRACE_JSON] as the expected values. - Return valid JSON only. No markdown, no commentary outside the JSON object. ## EXAMPLES [FEW_SHOT_EXAMPLES]
To adapt this template, replace the square-bracket placeholders with your actual trace data and configuration. The [TRACE_JSON] placeholder expects a structured trace object—this should come from your observability backend (e.g., LangSmith, Arize, Datadog, or a custom trace store). The threshold placeholders ([EMBEDDING_THRESHOLD_MS], etc.) let you define per-step latency budgets; if you omit them, the prompt falls back to comparing against a baseline trace provided in [BASELINE_TRACE_JSON]. The [FEW_SHOT_EXAMPLES] placeholder is optional but strongly recommended for production use—include one or two annotated trace-to-breakdown examples to stabilize the output format and anomaly detection logic. Before wiring this into an automated pipeline, validate the output JSON against the schema using a strict parser, and log any parse failures for human review. For high-stakes latency investigations (e.g., SLO violations affecting paying customers), always pair this prompt's output with raw trace visualizations and do not rely on the model's anomaly hypotheses without engineering confirmation.
Prompt Variables
Required inputs for the Latency Contribution by Retrieval Step Prompt. Each placeholder must be populated from trace data before the prompt can produce a reliable retrieval latency breakdown.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[TRACE_SPANS] | Raw span data from a single RAG trace containing start/end timestamps and operation names for embedding, vector search, reranking, and context assembly steps | {"spans": [{"operation": "embed_query", "start_ms": 0, "end_ms": 45}, {"operation": "vector_search", "start_ms": 45, "end_ms": 120}]} | Must be valid JSON array with at least one span. Each span requires operation, start_ms, and end_ms fields. Reject if timestamps are missing or negative. |
[GENERATION_LATENCY_MS] | Total model inference latency in milliseconds for the generation step, used as the baseline for comparing retrieval overhead | 850 | Must be a positive integer. Reject if zero, negative, or non-numeric. Compare against trace metadata to confirm this excludes retrieval time. |
[END_TO_END_LATENCY_MS] | Full request latency in milliseconds from user input to final token, used to calculate retrieval contribution as a percentage of total time | 1250 | Must be a positive integer greater than [GENERATION_LATENCY_MS]. Reject if smaller than generation latency, indicating data inconsistency. |
[RETRIEVAL_STEPS] | Ordered list of retrieval step names as they appear in the pipeline, used to label each row in the breakdown | ["embed_query", "vector_search", "rerank", "assemble_context"] | Must be a non-empty array of strings. Each step name must match an operation value in [TRACE_SPANS]. Reject if any step has no matching span. |
[BASELINE_LATENCY_BUDGET_MS] | Optional per-step latency budget in milliseconds for flagging anomalous retrieval steps | {"embed_query": 50, "vector_search": 80, "rerank": 100, "assemble_context": 30} | If provided, must be a valid JSON object with keys matching [RETRIEVAL_STEPS] and positive integer values. Null allowed if no budget comparison is needed. |
[TRACE_ID] | Unique trace identifier for logging and linking the analysis back to the source trace | "trace-4f8a2b1c-9d3e-4567-a1b2-c3d4e5f67890" | Must be a non-empty string. Used for audit trail and trace correlation. Reject if null or empty. |
[MODEL_ID] | Identifier for the generation model used in this trace, needed for context when comparing retrieval latency across model endpoints | "claude-sonnet-4-20250514" | Must be a non-empty string matching a known model identifier pattern. Used to group analyses by model for cross-model latency comparison. |
Implementation Harness Notes
How to wire the latency contribution prompt into a production observability pipeline for reliable, automated trace analysis.
This prompt is designed to be called programmatically, not pasted into a chat window. The primary integration point is your existing observability stack—Datadog, Grafana, Honeycomb, or a custom trace store. The harness should extract the relevant trace spans for a single request, serialize them into the [TRACE_JSON] placeholder, and invoke the model. Because latency analysis is time-sensitive during incidents, the harness must enforce a strict timeout on the model call (e.g., 15 seconds) and fall back to a simpler heuristic if the model doesn't return in time. Do not run this prompt on every request; target it at traces that breach a latency SLO threshold or are explicitly flagged by an on-call engineer. The output schema—a structured JSON breakdown of retrieval vs. generation latency—is designed to be ingested by a dashboard widget or incident response bot, so your harness must validate the JSON structure before forwarding it downstream.
Validation is the critical gate here. Before accepting the model's output, validate that the sum of the reported sub-step latencies (embedding, vector search, reranking, assembly) does not exceed the total retrieval latency, and that the total retrieval plus generation latency matches the end-to-end trace duration within a 5% tolerance. If validation fails, retry once with a simplified prompt that omits the [BASELINE_LATENCY_BUDGET] and asks only for the raw breakdown. Log both the raw trace and the model's output to your observability platform, indexed by trace ID, so you can audit for hallucinated latency numbers later. For model choice, use a low-latency model like claude-3-haiku or gpt-4o-mini because this is a structured extraction task, not a reasoning-heavy one. The prompt's [CONSTRAINTS] block should include a hard limit on output tokens (e.g., 300) to prevent verbose explanations from adding latency to your diagnostic loop.
Wire the validated output into your alerting and dashboarding layer. If the retrieval step accounts for more than 40% of the end-to-end latency budget, trigger a warning that routes to the search infrastructure team. If reranking alone exceeds 100ms, flag it for the model serving team. Avoid the temptation to run this prompt on every slow trace without sampling; batch analysis of historical traces should use a separate, cost-optimized pipeline. The immediate next step after implementing this harness is to create a runbook that maps each latency anomaly pattern to the responsible team and remediation action, so the prompt's output drives action rather than just generating a report.
Common Failure Modes
When analyzing latency contribution by retrieval step, these failure modes surface most often in production traces. Each card identifies a specific breakdown and how to guard against it before it reaches users.
Span Boundary Misattribution
What to watch: Retrieval latency gets blamed for generation slowness when trace spans overlap or lack clear boundaries. Embedding generation, vector search, reranking, and context assembly each need isolated spans—otherwise the breakdown is misleading. Guardrail: Enforce strict span start/stop instrumentation with unique span_id per retrieval substep. Validate that no two spans share timestamps before running the latency attribution prompt.
Cold-Start Embedding Inflation
What to watch: The first request after model deployment shows inflated embedding generation latency due to model loading or cache warming. This outlier skews averages and triggers false regression alerts. Guardrail: Exclude cold-start traces from latency analysis by filtering for requests where embedding_model_load_ms > 0 or where the first request in a deployment window exceeds the p95 baseline by more than 3x.
Reranking Dominance Without Thresholds
What to watch: Reranking latency grows linearly with candidate count and dominates the retrieval budget when too many candidates pass the initial vector search. Teams often miss this because they only monitor end-to-end retrieval time. Guardrail: Set a maximum candidate count for reranking (e.g., top 50) and log rerank_candidate_count as a trace attribute. Trigger a warning when reranking exceeds 40% of the total retrieval budget.
Context Assembly Serialization Bottleneck
What to watch: Context assembly—concatenating retrieved chunks, formatting citations, and injecting into the prompt template—becomes a hidden bottleneck when chunk sizes are large or when template rendering is synchronous. This step often lacks its own span. Guardrail: Instrument context assembly as a distinct span with attributes for chunk_count and total_assembled_tokens. Flag traces where assembly exceeds 10% of total retrieval latency.
Vector Store Network Latency Masking
What to watch: Vector search latency spikes due to network congestion, cross-region calls, or store-side throttling get reported as "search latency" without distinguishing transport from computation. The breakdown becomes useless for root-cause isolation. Guardrail: Split vector search spans into network_rtt_ms and store_compute_ms sub-attributes. If the store doesn't expose these, log client-side timing with a network_estimated flag and treat those traces as lower confidence.
Missing Baseline Drift Detection
What to watch: A retrieval step that is consistently 20% slower than last week goes unnoticed because there's no per-step baseline comparison. Teams only react when end-to-end latency breaches an SLO, missing gradual degradation. Guardrail: Store per-step latency baselines (p50, p95, p99) by prompt version and retrieval configuration. Include a baseline comparison column in the latency breakdown output, flagging any step where p95 exceeds baseline by more than 15%.
Evaluation Rubric
Use this rubric to test the quality of the latency breakdown output before deploying the prompt into an automated pipeline or dashboard. Each criterion targets a specific failure mode common in trace analysis prompts.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Step Completeness | All trace steps (embedding, search, rerank, assembly) are present in the output with a latency value or a null marker. | Missing a retrieval step that exists in the input trace spans. | Parse output JSON and assert that keys for all required steps exist in the breakdown object. |
Latency Sum Accuracy | The sum of per-step latencies equals the total retrieval latency within a 5ms tolerance. | Per-step latencies do not add up to the reported total, indicating a calculation or attribution error. | Compute the sum of all step-level latency values and compare against the total retrieval latency field using an absolute difference check. |
Unit Consistency | All latency values are reported in milliseconds as specified in the output schema. | A value appears in seconds or microseconds without conversion, causing order-of-magnitude errors. | Validate that every numeric latency field is between 0 and 600,000 (10 minutes) and reject values outside this range as unit mismatches. |
Anomaly Flagging Threshold | Steps exceeding the [LATENCY_THRESHOLD_MS] are flagged with | A step with latency 5x the threshold is not flagged, or a step under the threshold is incorrectly flagged. | Inject a trace with one known slow step and assert that the output contains exactly one anomaly flag on the correct step. |
Source Span Reference | Each step includes a | A step references a span ID not present in the input, or the span ID field is missing or null. | Extract all |
Overhead Attribution | Unaccounted latency between step end and next step start is attributed to an | Total latency minus sum of step latencies exceeds 10ms and no overhead explanation is provided. | Calculate the difference between total latency and the sum of step latencies; assert that an overhead field exists and its value matches the difference within tolerance. |
Baseline Comparison | Output includes a | The delta field is missing, zero when it should be non-zero, or calculated as absolute rather than relative to baseline. | Provide a baseline object and assert that each step's delta equals (actual - baseline) with correct sign. |
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
Use the base prompt with a single trace JSON dump and relaxed output validation. Replace [TRACE_SPANS_JSON] with raw span data from your observability tool. Accept markdown tables instead of strict JSON output during early exploration.
codeAnalyze the following trace spans and estimate latency contribution for each retrieval step. Output a markdown table with columns: Step, Estimated Latency (ms), Notes. [TRACE_SPANS_JSON]
Watch for
- Missing span types causing empty rows
- Overlapping spans counted twice
- No baseline comparison for what "normal" latency looks like

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