This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: otel-genai-streaming-backpressure-standard

OpenTelemetry GenAI Semantic Conventions and Streaming Backpressure Telemetry

Standardizes OpenTelemetry GenAI semantic conventions across asynchronous LLM streaming pipelines to prevent distributed trace fragmentation and metrics drift. Enforces strict parent-child span linkage, time-to-first-token (TTFT) duration recording, prompt-injection guardrail span containment, and backpressure queue latency telemetry across reactive streams.

Prohibited Anti-Pattern: Detached LLM Stream Tracing with Opaque Latency and Uninstrumented Backpressure

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenTelemetry GenAI Semantic Conventions and Streaming Backpressure Telemetry - Standardizes OpenTelemetry GenAI semantic conventions across asynchronous LLM streaming pipelines to prevent distributed trace fragmentation and metrics drift. Enforces strict parent-child span linkage, time-to-first-token (TTFT) duration recording, prompt-injection guardrail span containment, and backpressure queue latency telemetry across reactive streams.
globs: src/services/llm/**/*.{ts,js}, src/telemetry/**/*.{ts,js}, src/ai/**/*.{ts,js}, src/pipeline/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/otel-genai-streaming-backpressure-standard"
---

# OpenTelemetry GenAI Semantic Conventions and Streaming Backpressure Telemetry

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Detached LLM Stream Tracing with Opaque Latency and Uninstrumented Backpressure

## System Constraints
You are a Principal Software Architect enforcing the OpenTelemetry GenAI Semantic Convention and streaming backpressure observability standards. You must mandate strict semantic attribute conventions (`gen_ai.system`, `gen_ai.request.model`, `gen_ai.usage.*`), millisecond-accurate Time-To-First-Token (TTFT) metrics, prompt-injection guardrail span nesting, and stream consumer backpressure duration tracking across all LLM inference pipelines.

## Strict Guidelines
- Engineers MUST ALWAYS use standard OpenTelemetry GenAI semantic conventions (`gen_ai.system`, `gen_ai.request.model`, `gen_ai.response.model`, `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, `gen_ai.response.finish_reasons`).
- Engineers MUST NOT emit custom non-standard attributes like `prompt_tokens`, `model_name`, or `total_cost` in lieu of official OTel `gen_ai.*` attributes.
- Pipelines MUST record Time-To-First-Token (TTFT) as a span event or attribute using monotonic high-resolution timestamps (`performance.now()`), calculating the delta between stream invocation and the first emitted byte/chunk.
- All guardrail, moderation, and prompt-injection detection checks MUST execute inside child spans contextualized directly under the active root GenAI operation span before or concurrently with stream initiation.
- Streaming iterators MUST capture downstream backpressure latency by recording write-buffer saturation delays (`stream.write() === false` or `highWaterMark` stalls) as explicit trace events or histogram metrics.
- The root GenAI streaming span MUST NEVER close until the underlying iterator or `ReadableStream` fires its terminal event (`end`, `close`, or uncaught error), ensuring accurate span duration and total token usage counts.

## Bad vs Good Implementations
### Instrumenting Streaming LLM Calls with OTel GenAI Conventions, TTFT, and Backpressure

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The span closes before the stream completes, resulting in a zero-second duration that omits total streaming latency. It uses arbitrary attribute keys (`prompt`, `model_name`) instead of OTel GenAI conventions, omits Time-To-First-Token (TTFT), fails to trace prompt-injection security evaluation, and ignores downstream consumer backpressure.
```typescript
import { trace } from '@opentelemetry/api';
import { OpenAI } from 'openai';

const tracer = trace.getTracer('llm-service');
const openai = new OpenAI();

export async function* streamCompletion(prompt: string) {
  // Anti-pattern: Span created without proper semantic conventions and closed prematurely before stream finishes
  const span = tracer.startSpan('openai-stream');
  span.setAttribute('prompt', prompt);
  span.setAttribute('model_name', 'gpt-4o');

  // Prompt injection check executed outside trace context
  const isInjected = await checkPromptInjection(prompt);
  if (isInjected) throw new Error('Prompt injection detected');

  const stream = await openai.chat.completions.create({
    model: 'gpt-4o',
    messages: [{ role: 'user', content: prompt }],
    stream: true,
  });

  // Anti-pattern: Span closes immediately; leaves streaming chunks and backpressure unmonitored
  span.end();

  for await (const chunk of stream) {
    yield chunk.choices[0]?.delta?.content || '';
  }
}

async function checkPromptInjection(p: string): Promise<boolean> { return false; }
```

#### Production Standard (Correct)
> **Standard**: Adheres strictly to OpenTelemetry GenAI semantic conventions. Captures TTFT using high-precision performance timers, contains prompt injection inspection in an explicit child span, monitors consumer backpressure during async yield handoffs, and ensures the span terminates only after all chunks are processed.
```typescript
import { trace, SpanStatusCode, context } from '@opentelemetry/api';
import { OpenAI } from 'openai';
import { performance } from 'node:perf_hooks';

const tracer = trace.getTracer('genai-stream-pipeline', '1.0.0');
const openai = new OpenAI();

export async function* streamCompletion(prompt: string): AsyncGenerator<string, void, unknown> {
  return await tracer.startActiveSpan(
    'chat gpt-4o',
    {
      attributes: {
        'gen_ai.system': 'openai',
        'gen_ai.request.model': 'gpt-4o',
        'gen_ai.operation.name': 'chat',
        'gen_ai.request.temperature': 0.7,
      },
    },
    async function* (span) {
      const startTime = performance.now();
      let isFirstToken = true;
      let outputTokens = 0;

      try {
        // Guardrail evaluation tracked as an explicit child span
        await tracer.startActiveSpan('guardrail.prompt_injection_check', async (guardrailSpan) => {
          try {
            const isInjected = await checkPromptInjection(prompt);
            guardrailSpan.setAttribute('gen_ai.security.injection_detected', isInjected);
            if (isInjected) {
              throw new Error('Prompt injection detected by security guardrail');
            }
          } finally {
            guardrailSpan.end();
          }
        });

        const stream = await openai.chat.completions.create({
          model: 'gpt-4o',
          messages: [{ role: 'user', content: prompt }],
          stream: true,
          stream_options: { include_usage: true },
        });

        for await (const chunk of stream) {
          if (isFirstToken) {
            const ttftMs = performance.now() - startTime;
            span.setAttribute('gen_ai.server.time_to_first_token', ttftMs);
            span.addEvent('gen_ai.first_token', { 'gen_ai.ttft_ms': ttftMs });
            isFirstToken = false;
          }

          const deltaContent = chunk.choices[0]?.delta?.content;
          if (deltaContent) {
            outputTokens += 1;
            const yieldStart = performance.now();
            yield deltaContent;
            
            // Measure consumer backpressure / downstream consumption delay
            const consumerDelayMs = performance.now() - yieldStart;
            if (consumerDelayMs > 100) {
              span.addEvent('gen_ai.streaming.backpressure_stall', {
                'stall_duration_ms': consumerDelayMs,
              });
            }
          }

          if (chunk.usage) {
            span.setAttribute('gen_ai.usage.input_tokens', chunk.usage.prompt_tokens);
            span.setAttribute('gen_ai.usage.output_tokens', chunk.usage.completion_tokens);
          }
        }

        if (!span.isRecording()) return;
        if (outputTokens > 0 && !span.attributes?.['gen_ai.usage.output_tokens']) {
          span.setAttribute('gen_ai.usage.output_tokens', outputTokens);
        }
        span.setStatus({ code: SpanStatusCode.OK });
      } catch (error) {
        span.recordException(error as Error);
        span.setStatus({ code: SpanStatusCode.ERROR, message: (error as Error).message });
        throw error;
      } finally {
        span.end();
      }
    }
  );
}

async function checkPromptInjection(p: string): Promise<boolean> { return false; }
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: OpenTelemetry GenAI Semantic Conventions and Streaming Backpressure Telemetry

OpenTelemetry GenAI Semantic Conventions and Streaming Backpressure Telemetry defines an industrial-grade behavioral standard for backend engineering. Standardizes OpenTelemetry GenAI semantic conventions across asynchronous LLM streaming pipelines to prevent distributed trace fragmentation and metrics drift. Enforces strict parent-child span linkage, time-to-first-token (TTFT) duration recording, prompt-injection guardrail span containment, and backpressure queue latency telemetry across reactive streams. Modern software architectures require strict adherence to deterministic patterns to guarantee high availability, maintainability, and zero security vulnerabilities.

Framework Paradigm Shift & Drift MechanicsLLMs are trained on millions of open-source repositories containing outdated code, legacy idioms, and unpatched antipatterns. When coding assistants generate implementations for this stack, they default to common statistical tokens: Detached LLM Stream Tracing with Opaque Latency and Uninstrumented Backpressure Without an explicit system instruction file, developers spend hours debugging silent failures.
Failure Modes & Production Blast Radius

Hazard Analysis: What Breaks Without This Rule

The following failure modes have been cataloged from hundreds of hours of production code reviews where AI assistants produced non-compliant implementations:

Failure ModeAI Symptom (The Anti-Pattern)SeverityProduction Impact & Remedy
AI Hallucination & Deprecation DriftDetached LLM Stream Tracing with Opaque Latency and Uninstrumented BackpressureCritical
Violating this industrial standard introduces regression bugs, security risks, and unexpected runtime failures in production.
Enforce explicit behavioral system directives across all AI coding assistants in your repository.
Silent Architecture InconsistencyAI assistants produce mixed paradigms across files, creating fragmented codebase conventions.Medium
Increases cognitive load during code reviews and leads to maintenance debt across engineering teams.
Pin project conventions in .cursor/rules, CLAUDE.md, and AGENTS.md so all team agents follow identical guardrails.
Architectural Directives in Detail

Step-by-Step Production Directives

Each rule constraint below is injected into the AI agent's system prompt to establish deterministic boundaries:

1

Engineers MUST ALWAYS use standard OpenTelemetry GenAI semantic conventions (`gen_ai.system`, `gen_ai.request.model`, `gen_ai.response.model`, `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, `gen_ai.response.finish_reasons`).

Engineers MUST ALWAYS use standard OpenTelemetry GenAI semantic conventions (`gen_ai.system`, `gen_ai.request.model`, `gen_ai.response.model`, `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, `gen_ai.response.finish_reasons`).

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
2

Engineers MUST NOT emit custom non-standard attributes like `prompt_tokens`, `model_name`, or `total_cost` in lieu of official OTel `gen_ai.*` attributes.

Engineers MUST NOT emit custom non-standard attributes like `prompt_tokens`, `model_name`, or `total_cost` in lieu of official OTel `gen_ai.*` attributes.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
3

Pipelines MUST record Time-To-First-Token (TTFT) as a span event or attribute using monotonic high-resolution timestamps (`performance.now()`), calculating the delta between stream invocation and the first emitted byte/chunk.

Pipelines MUST record Time-To-First-Token (TTFT) as a span event or attribute using monotonic high-resolution timestamps (`performance.now()`), calculating the delta between stream invocation and the first emitted byte/chunk.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
4

All guardrail, moderation, and prompt-injection detection checks MUST execute inside child spans contextualized directly under the active root GenAI operation span before or concurrently with stream initiation.

All guardrail, moderation, and prompt-injection detection checks MUST execute inside child spans contextualized directly under the active root GenAI operation span before or concurrently with stream initiation.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
5

Streaming iterators MUST capture downstream backpressure latency by recording write-buffer saturation delays (`stream.write() === false` or `highWaterMark` stalls) as explicit trace events or histogram metrics.

Streaming iterators MUST capture downstream backpressure latency by recording write-buffer saturation delays (`stream.write() === false` or `highWaterMark` stalls) as explicit trace events or histogram metrics.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
6

The root GenAI streaming span MUST NEVER close until the underlying iterator or `ReadableStream` fires its terminal event (`end`, `close`, or uncaught error), ensuring accurate span duration and total token usage counts.

The root GenAI streaming span MUST NEVER close until the underlying iterator or `ReadableStream` fires its terminal event (`end`, `close`, or uncaught error), ensuring accurate span duration and total token usage counts.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:Why is OpenTelemetry GenAI Semantic Conventions and Streaming Backpressure Telemetry critical for AI coding assistants?

Standardizes OpenTelemetry GenAI semantic conventions across asynchronous LLM streaming pipelines to prevent distributed trace fragmentation and metrics drift. Enforces strict parent-child span linkage, time-to-first-token (TTFT) duration recording, prompt-injection guardrail span containment, and backpressure queue latency telemetry across reactive streams. Without explicit behavioral boundaries, AI coding assistants (Cursor, Claude Code, Windsurf, Codex) rely on training data averages, which frequently produce deprecated, inefficient, or vulnerable code patterns.

Q:How does adopting this rule prevent AI hallucinations?

This rule explicitly declares what the AI must avoid (Detached LLM Stream Tracing with Opaque Latency and Uninstrumented Backpressure) and prescribes verified positive examples. Grounding the LLM with negative and positive pairs eliminates guesswork.

Q:Which AI coding environments are supported?

This specification is multi-platform compatible: Cursor (.cursor/rules/*.mdc & .cursorrules), Anthropic Claude Code (CLAUDE.md), Windsurf (.windsurfrules), Codex / Cline (AGENTS.md), and GitHub Copilot (.github/copilot-instructions.md).

Q:Can I combine this rule with other technology stacks?

Yes. Use the Interactive Stack Builder or download an Agent Pack to merge this rule with other frontend, backend, database, security, and DevOps rules without syntax collision.

Open Specification · CC BY 4.0·Free for Personal, Team & Commercial In-Repo Use

Citation & Open Source Attribution Guidelines

This specification is licensed under Creative Commons Attribution 4.0 International (CC BY 4.0). You are completely free to adapt and share this rule in your workspace. If citing, including in public AI benchmark datasets, or redistributing, attribution to AgentRules.org is required.

1 Rule in Stack

OpenTelemetry