This prompt is designed for infrastructure engineers and AI SREs who need to programmatically detect latency threshold breaches across distributed trace spans. Use it when you have raw trace data from an observability platform (such as OpenTelemetry, Datadog, or Grafana Tempo) and need to identify which spans violated P50, P95, or P99 latency targets within a configurable evaluation window. The prompt expects structured span data as input and produces a breach report with timestamps, affected components, bottleneck attribution, and severity classification.
Prompt
Latency Threshold Breach Detection Prompt Template

When to Use This Prompt
Defines the operational context, required inputs, and constraints for using the Latency Threshold Breach Detection Prompt in a production monitoring pipeline.
This is not a dashboard replacement or a real-time alerting system. It is a diagnostic and analysis tool that should be wired into a monitoring pipeline where human review or automated escalation can act on the output. The prompt assumes spans include start timestamps, duration in milliseconds, service names, and operation names. Before wiring this into production, validate that your trace data conforms to this schema and that your percentile targets are calibrated against historical baselines—running breach detection against misconfigured thresholds will generate noise that erodes on-call trust.
Do not use this prompt when you lack structured trace data, when you need sub-millisecond precision, or when the evaluation window is undefined. It is also unsuitable for real-time stream processing where per-span latency decisions must happen inline; this prompt is designed for batch evaluation over a completed window. If your traces lack service-name or operation-name fields, the bottleneck attribution step will degrade and produce generic rather than actionable output. For high-severity breaches affecting customer-facing SLOs, always route the output through a human review step before triggering an incident.
Use Case Fit
Where the Latency Threshold Breach Detection Prompt Template works, where it fails, and what you must have in place before relying on it.
Good Fit: Structured Trace Spans
Use when: your observability pipeline emits structured spans with duration_ms, operation_name, and parent_span_id fields. The prompt excels at correlating P95 breaches to specific service boundaries. Guardrail: validate span schema completeness before feeding traces to the prompt—missing duration_ms fields produce silent false negatives.
Bad Fit: Unsampled or Aggregated Data
Avoid when: you only have pre-aggregated metrics or sampled traces. The prompt requires raw span-level data to attribute latency to specific steps. Feeding it dashboard aggregates produces hallucinated bottleneck attributions. Guardrail: reject inputs that lack per-span timing data and escalate to metric-based alerting instead.
Required Input: Percentile Configuration
What to watch: the prompt needs explicit P50/P95/P99 targets and a window size. Without these, it defaults to arbitrary thresholds that may not match your SLOs. Guardrail: always pass [PERCENTILE_TARGETS] and [EVALUATION_WINDOW_MINUTES] as explicit parameters, never rely on prompt defaults.
Operational Risk: Noisy Alerts from Transient Spikes
What to watch: single-span P99 breaches during cold starts or cache misses trigger alerts that self-resolve. This erodes on-call trust. Guardrail: require sustained breach duration (e.g., 3 consecutive evaluation windows) before escalation, and include a [MIN_BREACH_DURATION] parameter in the prompt template.
Operational Risk: Missing Baseline Comparison
What to watch: the prompt identifies breaches but cannot distinguish a new regression from a known slow endpoint without historical context. Guardrail: feed a [BASELINE_WINDOW] of recent trace data alongside the evaluation window so the prompt can flag deviations from normal latency profiles, not just threshold violations.
Bad Fit: Multi-Tenant Attribution Gaps
Avoid when: latency spikes are caused by noisy-neighbor effects in shared infrastructure that traces cannot attribute. The prompt will blame the slowest span rather than the underlying resource contention. Guardrail: pair trace analysis with infrastructure metrics (CPU, memory, I/O) and use this prompt only for application-layer attribution.
Copy-Ready Prompt Template
A copy-ready prompt template for detecting latency threshold breaches across trace spans and attributing bottlenecks to specific services and operations.
This prompt template is designed to be dropped directly into your observability workflow. It expects structured trace span data as input and produces a strict JSON report of all latency threshold breaches. The template enforces attribution discipline: every breach must be tied to a specific service and operation present in the input data. It will not invent spans, durations, or causal relationships not supported by the evidence. If a span lacks required fields for analysis, the template instructs the model to flag it as incomplete rather than guessing.
textYou are a production observability analyst. Your task is to analyze the provided trace span data and identify all latency threshold breaches across P50, P95, and P99 percentiles within the specified evaluation window. ## INPUT DATA [TRACE_SPAN_DATA] ## CONFIGURATION - Evaluation Window: [EVALUATION_WINDOW_START] to [EVALUATION_WINDOW_END] - P50 Threshold (ms): [P50_THRESHOLD] - P95 Threshold (ms): [P95_THRESHOLD] - P99 Threshold (ms): [P99_THRESHOLD] ## OUTPUT SCHEMA Return a valid JSON object with this exact structure: { "evaluation_window": { "start": "ISO8601 timestamp", "end": "ISO8601 timestamp" }, "thresholds": { "p50_ms": number, "p95_ms": number, "p99_ms": number }, "breaches": [ { "breach_id": "string", "timestamp": "ISO8601 timestamp of breach detection", "percentile": "P50 | P95 | P99", "observed_latency_ms": number, "threshold_ms": number, "excess_ms": number, "severity": "LOW | MEDIUM | HIGH | CRITICAL", "affected_service": "string", "affected_operation": "string", "span_id": "string", "trace_id": "string", "attribution": { "bottleneck_service": "string", "bottleneck_operation": "string", "step_level_detail": "string explaining where latency accumulated" } } ], "incomplete_spans": [ { "span_id": "string", "trace_id": "string", "missing_fields": ["field_name"], "reason": "string explaining why analysis was not possible" } ], "summary": { "total_spans_analyzed": number, "total_breaches": number, "breaches_by_percentile": { "p50": number, "p95": number, "p99": number }, "breaches_by_severity": { "low": number, "medium": number, "high": number, "critical": number }, "incomplete_spans_count": number } } ## CONSTRAINTS [CONSTRAINTS] - Do not invent spans, services, operations, or durations not present in the input data. - If a span lacks service name, operation name, or duration fields, flag it in `incomplete_spans` rather than guessing. - Severity classification: LOW (excess < 10% of threshold), MEDIUM (10-25%), HIGH (25-50%), CRITICAL (>50%). - Attribution must reference specific spans and operations from the input data. - If multiple spans contribute to a single breach, identify the primary bottleneck. - Return only valid JSON. No markdown fences, no commentary.
To adapt this template, replace the square-bracket placeholders with your specific configuration. [TRACE_SPAN_DATA] should contain your structured span data in JSON format, including at minimum span_id, trace_id, service_name, operation_name, duration_ms, and timestamp fields. [EVALUATION_WINDOW_START] and [EVALUATION_WINDOW_END] define the time range for analysis. The three threshold values set your latency SLOs. [CONSTRAINTS] can be extended with additional rules, such as excluding specific services from analysis or adding custom severity mappings. Before deploying this prompt into an automated monitoring pipeline, validate the output against known breach scenarios to ensure the severity classification and attribution logic matches your operational expectations. For high-severity breaches, route the output to a human reviewer before triggering automated incident response.
Prompt Variables
Required inputs for the Latency Threshold Breach Detection Prompt Template. Each variable must be populated before the prompt is sent to the model. Validation notes describe how to verify the input is well-formed before execution.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[TRACE_SPANS_JSON] | Raw trace span data containing start/end timestamps, operation names, and parent-child relationships for analysis | {"spans": [{"spanId": "abc123", "operationName": "llm_completion", "startTime": "2025-01-15T10:23:01.000Z", "durationMs": 4200, "parentSpanId": null}]} | Parse check: valid JSON array with required fields spanId, durationMs, startTime. Reject if spans array is empty or missing durationMs field. |
[LATENCY_THRESHOLDS_MS] | P50, P95, and P99 latency thresholds in milliseconds that define acceptable performance boundaries per operation type | {"llm_completion": {"p50": 2000, "p95": 5000, "p99": 8000}, "vector_search": {"p50": 100, "p95": 300, "p99": 500}} | Schema check: object with operation names as keys, each containing p50, p95, p99 integer values. Reject if any percentile threshold is missing or zero. |
[EVALUATION_WINDOW_MINUTES] | Time window in minutes over which latency breaches should be evaluated, defining the scope of the analysis period | 15 | Range check: integer between 1 and 1440. Reject if window exceeds available trace data timespan or is less than 1 minute. |
[PERCENTILE_OF_INTEREST] | Specific percentile target for breach detection focus, typically p95 or p99 for latency-sensitive workflows | p95 | Enum check: must be one of p50, p95, p99. Reject if value does not match threshold keys in [LATENCY_THRESHOLDS_MS]. |
[MIN_BREACH_COUNT] | Minimum number of breaches required before an alert is triggered, preventing noise from isolated slow requests | 3 | Range check: integer >= 1. Reject if value exceeds total span count in evaluation window. |
[OUTPUT_SCHEMA] | Expected JSON structure for breach detection results including timestamps, affected components, and bottleneck attribution | {"breaches": [{"timestamp": "ISO8601", "operationName": "string", "durationMs": "number", "thresholdExceeded": "string", "bottleneckStep": "string|null"}]} | Schema check: valid JSON Schema or example object. Reject if missing required fields timestamp, operationName, durationMs, thresholdExceeded. |
[COMPONENT_MAP] | Mapping of span operation names to human-readable component labels for bottleneck attribution in output | {"llm_completion": "LLM Inference Service", "vector_search": "Vector DB Query", "embedding_generation": "Embedding API"} | Parse check: valid JSON object with string keys and string values. Reject if any operation name from trace spans is missing from the map. |
Implementation Harness Notes
How to wire the latency threshold breach detection prompt into an observability pipeline with validation, retries, and alert routing.
The latency threshold breach detection prompt is designed to operate as a batch analysis step within an existing observability pipeline, not as a real-time streaming processor. Feed it a window of trace spans extracted from your tracing backend (Jaeger, Grafana Tempo, Datadog APM, or similar) at a cadence that matches your SLO evaluation interval—typically every 5 to 15 minutes. The prompt expects pre-aggregated span data with timestamps, duration values, service names, and operation identifiers. Do not send raw, unsampled trace payloads; pre-filter to the relevant services and time window before invoking the model.
Integration flow: (1) A scheduled job queries your trace store for spans in the evaluation window, filtered by service and operation. (2) The span data is serialized into the [TRACE_SPANS] input block as a structured JSON array with fields: span_id, service, operation, duration_ms, start_time, parent_span_id, and status. (3) The prompt is invoked with [PERCENTILE_THRESHOLDS] set to your SLO targets (e.g., {"p50": 200, "p95": 1000, "p99": 3000}) and [WINDOW_CONFIG] specifying the evaluation window size and granularity. (4) The model returns a structured JSON payload with breach events, affected components, and bottleneck attribution. (5) A post-processing validator checks that every breach entry contains a timestamp, percentile, observed_value, threshold, and affected_service before the output is forwarded to your alerting system.
Validation and retry logic: Implement a schema validator that rejects outputs missing required fields or containing malformed timestamps. If validation fails, retry once with the same input and an explicit [CONSTRAINTS] amendment flagging the missing field. If the retry also fails, log the raw output and escalate to the on-call channel with a latency_breach_detection_failed event. For high-severity environments, add a human-review gate before auto-paging: route breach events with severity: critical to a review queue where an SRE confirms the bottleneck attribution before an incident is declared. This prevents alert fatigue from transient spikes that the model may over-classify.
Model choice and cost: This task requires strong structured output adherence and numerical reasoning. Use a model with reliable JSON mode and low hallucination rates on data-extraction tasks—GPT-4o, Claude 3.5 Sonnet, or equivalent. Avoid smaller models that may conflate percentile values or fabricate breach events when span data is sparse. Token consumption scales with the number of spans in the window; if you are processing thousands of spans per evaluation cycle, pre-aggregate to service-level duration distributions rather than sending individual spans. Cache the system prompt prefix across invocations to reduce per-request cost.
Alert routing and observability: Map the prompt's output fields directly to your alerting system's data model. The breach_id should be a deterministic hash of window_start + percentile + service to enable deduplication in your alert manager. Attach the full prompt input and output as metadata on the alert so incident responders can trace the breach back to the source spans. Log every invocation—input, output, latency, token count, and validation result—to your prompt observability store for later audit and threshold tuning. If breach frequency increases after a model or prompt version change, compare invocation logs to distinguish a real latency regression from a detection sensitivity shift.
Expected Output Contract
Defines the structured JSON output from the Latency Threshold Breach Detection Prompt. Use this contract to validate the LLM's response before routing to alerting systems or dashboards.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
analysis_id | string (UUID v4) | Must match regex: ^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$ | |
evaluation_window | object | Must contain 'start_time' and 'end_time' as ISO 8601 strings. 'end_time' must be after 'start_time'. | |
target_percentile | string | Must be one of: 'p50', 'p95', 'p99'. Case-sensitive. | |
breach_events | array of objects | Each object must have 'timestamp' (ISO 8601), 'component' (string), 'measured_latency_ms' (number > 0), and 'threshold_ms' (number > 0). Array can be empty if no breaches. | |
bottleneck_attribution | object | Must contain 'primary_component' (string) and 'confidence_score' (number between 0.0 and 1.0). 'confidence_score' must be >= 0.7 for automated alerting. | |
affected_spans | array of strings | Each string must match a valid span ID format from the input trace data. Null or empty array is allowed if no spans are affected. | |
summary | string | Must be non-empty. Length must be between 10 and 500 characters. Must reference the target percentile and primary bottleneck component. |
Common Failure Modes
Latency threshold breach detection is only as reliable as its configuration and input data. These are the most common failure modes when deploying detection prompts in production, and the practical steps to prevent them.
Percentile Misconfiguration
What to watch: The prompt is configured for P95 but the SLO is defined on P99, or the window size (e.g., 5 minutes) is too small to be statistically meaningful. This generates false positives or misses actual breaches. Guardrail: Validate the [PERCENTILE] and [WINDOW_SIZE] parameters against the formal SLO definition before deployment. Add a pre-execution check that rejects windows with fewer than 100 data points.
Cold Start and Missing Baselines
What to watch: A new deployment or a traffic spike to a cold component has no historical baseline, causing the prompt to either flag everything as a breach or miss latency degradation entirely. Guardrail: Require a minimum baseline duration (e.g., 1 hour of stable traffic) before breach evaluation begins. If the baseline is missing, the prompt should output an INSUFFICIENT_DATA status rather than a false negative.
Span Attribution Drift
What to watch: A slow database call is attributed to the upstream API gateway span due to a tracing instrumentation gap. The prompt identifies the wrong component as the bottleneck, sending the on-call engineer to the wrong service. Guardrail: Include a [SPAN_ATTRIBUTION_RULES] input that defines parent-child relationships. The prompt must cross-reference the affected_components output against a known service map and flag any component not in the map for human review.
Alert Storms from Downstream Cascades
What to watch: A single root-cause latency spike in a core service triggers breaches across dozens of dependent services, overwhelming the alerting channel with duplicate notifications. Guardrail: The prompt must include a deduplication step that groups breaches by a common root span ID. Output a single alert with a cascaded_components list rather than one alert per affected service.
Threshold Hard-Coding Drift
What to watch: The latency threshold (e.g., 200ms) is hard-coded in the prompt template and not updated when the service's performance profile changes after a release. This causes the alert to go silent or fire continuously. Guardrail: Always inject the threshold as a dynamic [LATENCY_THRESHOLD_MS] variable sourced from a configuration store. Add a periodic audit check that compares the configured threshold against the actual trailing P50 to detect stale values.
Batch Trace Processing Lag
What to watch: The trace ingestion pipeline is delayed, so the prompt evaluates a window from 10 minutes ago. The breach alert fires after the incident has already self-resolved, eroding trust in the monitoring system. Guardrail: The prompt must check the trace_ingestion_timestamp against the current wall-clock time. If the lag exceeds a configured [MAX_INGESTION_LAG_SECONDS], the output must include a data_freshness_warning field and suppress the alert severity by one level.
Evaluation Rubric
Criteria for testing the latency threshold breach detection prompt before production deployment. Each row defines a pass standard, a failure signal, and a concrete test method.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Breach Timestamp Accuracy | All returned timestamps fall within the specified evaluation window and correspond to actual trace spans exceeding the configured percentile threshold. | Timestamps outside the evaluation window or not associated with any trace span are present in the output. | Validate each timestamp against the source trace data and the [EVALUATION_WINDOW] parameter using a deterministic script. |
Percentile Calculation Correctness | The P50, P95, and P99 values reported match a reference implementation (e.g., numpy percentile) to within a 5ms tolerance. | Calculated percentile values deviate by more than 5ms from the reference implementation or are mathematically impossible (e.g., P50 > P95). | Run a sidecar calculation on the raw span durations and assert near-equality with the model's output. |
Affected Component Identification | Every breach is attributed to a specific component name (e.g., 'api-gateway', 'llm-inference') that exists in the source trace metadata. | A breach is attributed to a generic label like 'unknown', a null value, or a component not present in the input trace data. | Cross-reference the output's component list against the unique |
Bottleneck Attribution Logic | The identified bottleneck step is the span with the highest self-time within the slowest trace segment, and the explanation references this metric. | The bottleneck explanation blames a downstream dependency without evidence or identifies a span with low self-time as the primary cause. | Inject a synthetic trace with a known bottleneck span and verify the model correctly identifies it and provides a self-time-based justification. |
Output Schema Compliance | The output is valid JSON that strictly matches the [OUTPUT_SCHEMA] definition, including all required fields and correct data types. | The output is missing required fields, contains extra untyped fields, or uses string types where numbers are expected. | Validate the model's raw output string against the [OUTPUT_SCHEMA] using a JSON Schema validator. Reject on failure. |
Window Size Parameter Handling | The analysis strictly respects the [WINDOW_SIZE_MINUTES] parameter, ignoring all spans with start times outside this rolling window. | Spans from outside the configured window are included in the analysis, leading to false breach counts. | Provide a trace dataset with spans just inside and just outside the window boundary and assert that boundary spans are handled correctly. |
Handling of No-Breach Scenarios | When no span exceeds the threshold, the output returns an empty breach list and a summary stating no violations were detected, without hallucinating data. | The model fabricates a breach, returns a non-empty list, or generates an error message instead of a valid empty response. | Run the prompt against a clean trace dataset with all spans under the threshold and assert that the |
Multi-Percentile Configuration | When multiple percentiles are requested in [PERCENTILE_CONFIG], the output correctly reports separate breach lists and thresholds for each one. | The output conflates results for different percentiles or applies the same threshold calculation to all of them. | Test with a configuration requesting both P95 and P99 thresholds and verify the output contains distinct sections with correct values for each. |
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 file. Replace [INPUT_TRACE_SPANS] with a raw JSON array of spans from one session. Hardcode [LATENCY_THRESHOLD_MS] to a single value (e.g., 500) and [PERCENTILE_TARGET] to p95. Skip schema validation and output the model's raw JSON response for manual inspection.
Watch for
- The model may invent breach timestamps not present in the trace
- Percentile calculations may be approximated rather than computed from sorted data
- Span attribution can be vague without explicit step-level IDs in the input

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