This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
devopscritical PriorityID: opentelemetry-ebpf-profiling-flamegraph-correlation-standard

OpenTelemetry eBPF Continuous Profiling & Flamegraph Trace Correlation Standard

Enforces sub-1% CPU/memory overhead budgets for continuous eBPF kernel profiling in production while mandating deterministic correlation of runtime flamegraphs to OpenTelemetry trace spans. Prevents host performance degradation, harmonic sampling distortion, and orphaned profile telemetry by decoupling symbolication and synchronizing BPF task maps with distributed trace context.

Prohibited Anti-Pattern: Unbounded In-Kernel Sampling and Detached Flamegraphs Lacking Distributed Trace Context

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenTelemetry eBPF Continuous Profiling & Flamegraph Trace Correlation Standard - Enforces sub-1% CPU/memory overhead budgets for continuous eBPF kernel profiling in production while mandating deterministic correlation of runtime flamegraphs to OpenTelemetry trace spans. Prevents host performance degradation, harmonic sampling distortion, and orphaned profile telemetry by decoupling symbolication and synchronizing BPF task maps with distributed trace context.
globs: **/otel-collector*.{yaml,yml}, **/daemonset*.{yaml,yml}, **/profiling*.{ts,js,go}, src/telemetry/**/*.{ts,js,go}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/opentelemetry-ebpf-profiling-flamegraph-correlation-standard"
---

# OpenTelemetry eBPF Continuous Profiling & Flamegraph Trace Correlation Standard

> **Severity**: CRITICAL | **Category**: devops
> **Anti-Pattern Warning**: Unbounded In-Kernel Sampling and Detached Flamegraphs Lacking Distributed Trace Context

## System Constraints
You are a Principal Observability Architect and SRE enforcing strict OpenTelemetry continuous eBPF profiling standards. All continuous CPU and memory profiling deployments must maintain host overhead strictly under 1.0% CPU and 128MB RAM, use prime-number sampling intervals to avoid harmonic aliasing, defer DWARF/native symbol resolution out-of-band, and inject active TraceID and SpanID context into eBPF stack traces for deterministic flamegraph correlation within distributed traces.

## Strict Guidelines
- Engineers MUST ALWAYS bound eBPF continuous sampling rates to non-harmonic prime frequencies (e.g., 19 Hz to 49 Hz) to cap kernel execution overhead strictly below 1% of total node CPU.
- Engineers MUST NOT execute native DWARF symbol resolution, stack unwinding symbol lookups, or demangling synchronously inside node-level eBPF agents or kernel space.
- Services MUST inject current OpenTelemetry `trace_id` and `span_id` into eBPF thread/task correlation maps via user-space runtime thread context or BPF uprobes.
- Engineers MUST configure continuous profiling ring buffers with bounded memory limits (<128MB per host) and backpressure drop counters instead of blocking critical threads.
- Profiling pipelines MUST aggregate collapsed stack traces over deterministic windows (minimum 10s intervals) before streaming via OTLP/Profiles to downstream backends.
- Continuous profiling telemetry MUST NEVER generate spans independently; it MUST correlate directly with existing active distributed spans via `ProfileId` or flamegraph link attributes.

## Bad vs Good Implementations
### TypeScript OpenTelemetry Runtime Context Bridging for eBPF Profiler

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Samples synchronously at 1000 Hz, inducing high CPU/memory overhead (>10%) and harmonic aliasing with system timers. Captures raw string stack traces and writes to disk with zero OTel TraceID/SpanID correlation, preventing automated flamegraph rendering on spans.
```typescript
import { trace } from '@opentelemetry/api';
import * as fs from 'fs';

// ANTI-PATTERN: Spawning unthrottled userspace profiler with synchronous symbol lookup
// and detached execution that fails to link flamegraph spans with active distributed traces.
export function runProfilingWindow(durationMs: number) {
  const span = trace.getActiveSpan();
  // Synchronous userspace sampling at 1000Hz causes >10% CPU overhead
  const samples: string[] = [];
  const interval = setInterval(() => {
    const stack = new Error().stack; // Costly string allocations
    if (stack) samples.push(stack);
  }, 1); // 1000 Hz harmonic with OS scheduler

  setTimeout(() => {
    clearInterval(interval);
    // Written to disk detached from OTel span with no trace correlation
    fs.writeFileSync('/tmp/profile.raw', samples.join('\n'));
    span?.end();
  }, durationMs);
}
```

#### Production Standard (Correct)
> **Standard**: Publishes current TraceId and SpanId to a deterministic, low-overhead in-memory context readable by an eBPF daemon, keeping runtime instrumentation overhead below 0.1% while guaranteeing that host-level eBPF flamegraphs are linked to corresponding OTel spans.
```typescript
import { trace, context } from '@opentelemetry/api';
import { AsyncLocalStorage } from 'async_hooks';

// Enterprise Guardrail: Low-overhead thread-local trace correlation for eBPF agent
interface BpfTraceContext {
  traceIdHex: string;
  spanIdHex: string;
  active: boolean;
}

// Direct write to shared TLS/pinned memory mapped region readable by eBPF uprobes/task inspectors
class EbpfContextBridge {
  private static instance: EbpfContextBridge;
  private correlationMap = new Map<number, BpfTraceContext>();

  public static getInstance(): EbpfContextBridge {
    if (!EbpfContextBridge.instance) {
      EbpfContextBridge.instance = new EbpfContextBridge();
    }
    return EbpfContextBridge.instance;
  }

  public syncCurrentTraceContext(): void {
    const activeSpan = trace.getSpan(context.active());
    if (!activeSpan) return;

    const spanContext = activeSpan.spanContext();
    const threadId = process.pid; // Or worker thread ID

    // Updates local memory mapped structure monitored by continuous eBPF sampler
    this.correlationMap.set(threadId, {
      traceIdHex: spanContext.traceId,
      spanIdHex: spanContext.spanId,
      active: activeSpan.isRecording()
    });
  }

  public clearTraceContext(): void {
    this.correlationMap.delete(process.pid);
  }
}

export async function executeTraceCorrelatedOperation<T>(
  name: string,
  operation: () => Promise<T>
): Promise<T> {
  const tracer = trace.getTracer('ebpf-continuous-profiler');
  return tracer.startActiveSpan(name, async (span) => {
    const bridge = EbpfContextBridge.getInstance();
    bridge.syncCurrentTraceContext();
    try {
      return await operation();
    } finally {
      bridge.clearTraceContext();
      span.end();
    }
  });
}
```

### OpenTelemetry Collector Continuous Profiling DaemonSet Configuration

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Configures a non-prime 1000 Hz sampling rate causing severe CPU consumption and aliasing. Enables synchronous local DWARF symbolization on the host DaemonSet, risking OOM crashes and exceeding the 1% overhead budget.
```yaml
# ANTI-PATTERN: High-frequency harmonic sampling, local synchronous symbolization,
# and unbounded memory queues causing massive cluster resource starvation.
receivers:
  ebpf_profiler:
    sampling_frequency: 1000 # 1000 Hz generates > 15% CPU load
    unwind_strategy: dwarf
    symbolize_locally: true # Heavy memory and binary DWARF parsing in DaemonSet
exporters:
  otlp:
    endpoint: "profiling-backend:4317"
service:
  pipelines:
    profiles:
      receivers: [ebpf_profiler]
      exporters: [otlp]
```

#### Production Standard (Correct)
> **Standard**: Applies a prime 19 Hz sampling rate, caps ring buffer size at 32MB, enables trace correlation, and delegates symbol resolution out-of-band to prevent node memory spikes and ensure overhead remains well under 1%.
```yaml
# Enterprise Guardrail: eBPF Continuous Profiling with strict sub-1% CPU & trace span correlation
receivers:
  ebpf_profiler:
    sampling_frequency: 19 # Prime number frequency avoids harmonic sync; caps CPU < 0.5%
    enable_trace_correlation: true
    correlation_attributes:
      - trace_id
      - span_id
    ring_buffer_size_mb: 32
    drop_on_backpressure: true
    symbolize_locally: false # Symbol resolution deferred out-of-band

processors:
  batch/profiles:
    send_batch_size: 512
    timeout: 10s
  memory_limiter:
    check_interval: 1s
    limit_percentage: 75
    spike_limit_percentage: 15

exporters:
  otlp/profiles:
    endpoint: "symbolicator-collector.monitoring.svc.cluster.local:4317"
    tls:
      insecure: false

service:
  pipelines:
    profiles:
      receivers: [ebpf_profiler]
      processors: [memory_limiter, batch/profiles]
      exporters: [otlp/profiles]
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: OpenTelemetry eBPF Continuous Profiling & Flamegraph Trace Correlation Standard

OpenTelemetry eBPF Continuous Profiling & Flamegraph Trace Correlation Standard defines an industrial-grade behavioral standard for devops engineering. Enforces sub-1% CPU/memory overhead budgets for continuous eBPF kernel profiling in production while mandating deterministic correlation of runtime flamegraphs to OpenTelemetry trace spans. Prevents host performance degradation, harmonic sampling distortion, and orphaned profile telemetry by decoupling symbolication and synchronizing BPF task maps with distributed trace context. 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: Unbounded In-Kernel Sampling and Detached Flamegraphs Lacking Distributed Trace Context 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 DriftUnbounded In-Kernel Sampling and Detached Flamegraphs Lacking Distributed Trace ContextCritical
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 bound eBPF continuous sampling rates to non-harmonic prime frequencies (e.g., 19 Hz to 49 Hz) to cap kernel execution overhead strictly below 1% of total node CPU.

Engineers MUST ALWAYS bound eBPF continuous sampling rates to non-harmonic prime frequencies (e.g., 19 Hz to 49 Hz) to cap kernel execution overhead strictly below 1% of total node CPU.

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 execute native DWARF symbol resolution, stack unwinding symbol lookups, or demangling synchronously inside node-level eBPF agents or kernel space.

Engineers MUST NOT execute native DWARF symbol resolution, stack unwinding symbol lookups, or demangling synchronously inside node-level eBPF agents or kernel space.

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

Services MUST inject current OpenTelemetry `trace_id` and `span_id` into eBPF thread/task correlation maps via user-space runtime thread context or BPF uprobes.

Services MUST inject current OpenTelemetry `trace_id` and `span_id` into eBPF thread/task correlation maps via user-space runtime thread context or BPF uprobes.

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

Engineers MUST configure continuous profiling ring buffers with bounded memory limits (<128MB per host) and backpressure drop counters instead of blocking critical threads.

Engineers MUST configure continuous profiling ring buffers with bounded memory limits (<128MB per host) and backpressure drop counters instead of blocking critical threads.

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

Profiling pipelines MUST aggregate collapsed stack traces over deterministic windows (minimum 10s intervals) before streaming via OTLP/Profiles to downstream backends.

Profiling pipelines MUST aggregate collapsed stack traces over deterministic windows (minimum 10s intervals) before streaming via OTLP/Profiles to downstream backends.

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

Continuous profiling telemetry MUST NEVER generate spans independently

Continuous profiling telemetry MUST NEVER generate spans independently; it MUST correlate directly with existing active distributed spans via `ProfileId` or flamegraph link 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.
Technical Questions & Answers

Frequently Asked Technical Questions

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

Q:Why is OpenTelemetry eBPF Continuous Profiling & Flamegraph Trace Correlation Standard critical for AI coding assistants?

Enforces sub-1% CPU/memory overhead budgets for continuous eBPF kernel profiling in production while mandating deterministic correlation of runtime flamegraphs to OpenTelemetry trace spans. Prevents host performance degradation, harmonic sampling distortion, and orphaned profile telemetry by decoupling symbolication and synchronizing BPF task maps with distributed trace context. 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 (Unbounded In-Kernel Sampling and Detached Flamegraphs Lacking Distributed Trace Context) 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