This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
devopscritical PriorityID: otel-ebpf-flow-tail-sampling-governor

OpenTelemetry eBPF Dynamic Flow Tail-Sampling Kernel Governor

Enforces in-kernel ring-buffer backpressure and dynamic tail-sampling for high-cardinality eBPF network flow telemetry during microbursts. Prevents user-space collector out-of-memory (OOM) crashes by shedding deterministic, healthy flow events in kernel space while guaranteeing 100% trace extraction for anomalous, high-latency, or errored socket transactions.

Prohibited Anti-Pattern: Unbounded Head-Sampling Ring Buffer Emission Leading to Collector Node OOM

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenTelemetry eBPF Dynamic Flow Tail-Sampling Kernel Governor - Enforces in-kernel ring-buffer backpressure and dynamic tail-sampling for high-cardinality eBPF network flow telemetry during microbursts. Prevents user-space collector out-of-memory (OOM) crashes by shedding deterministic, healthy flow events in kernel space while guaranteeing 100% trace extraction for anomalous, high-latency, or errored socket transactions.
globs: **/*.c, **/*.bpf.c, **/*.bpf.h, pkg/ebpf/**/*.go, src/collector/**/*.rs, src/telemetry/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/otel-ebpf-flow-tail-sampling-governor"
---

# OpenTelemetry eBPF Dynamic Flow Tail-Sampling Kernel Governor

> **Severity**: CRITICAL | **Category**: devops
> **Anti-Pattern Warning**: Unbounded Head-Sampling Ring Buffer Emission Leading to Collector Node OOM

## System Constraints
You are a Principal Observability and Systems Architect enforcing kernel-level telemetry governance. Uncontrolled socket telemetry extraction via eBPF can easily exhaust memory bandwidth and crash collector daemons under TCP microburst conditions. You must enforce two-phase tail-sampling: compute latency windows and TCP error states directly in BPF maps, deferring trace emission until connection close or threshold breach, and dropping nominal keep-alive flows before they cross into user space.

## Strict Guidelines
- Engineers MUST ALWAYS implement local BPF hash maps (e.g., BPF_MAP_TYPE_HASH or BPF_MAP_TYPE_LRU_HASH) to hold active socket state until a transaction terminates or exceeds an anomaly threshold.
- Engineers MUST NOT forward raw TCP packet headers directly to user space via BPF_MAP_TYPE_PERF_EVENT_ARRAY or BPF_MAP_TYPE_RINGBUF prior to classification.
- Kernels MUST dynamically apply an adaptive token bucket governor that downsamples nominal HTTP 200 / TCP FIN flows when collector consumer queue depth breaches the high-watermark threshold (>= 80%).
- Services MUST guarantee deterministic delivery of telemetry frames tagged with TCP retransmissions (TCP_CA_Loss), socket-level errors (sk_err != 0), or latencies exceeding service-level SLO thresholds.
- Collectors MUST expose a shared memory or atomic state flag (via BPF_MAP_TYPE_ARRAY) communicating user-space heap pressure back to the in-kernel filter for real-time backpressure.

## Bad vs Good Implementations
### In-Kernel Adaptive Sampling vs. Indiscriminate Head-Sampling

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Emitting an event per payload segment floods the ring buffer during high-throughput microbursts. This exhausts collector memory buffers and causes catastrophic telemetry loss via user-space OOM termination without capturing diagnostic context.
```c
// BAD: Emits an event on every single socket transmission without state or burst protection
SEC("kprobe/tcp_sendmsg")
int BPF_KPROBE(trace_tcp_sendmsg, struct sock *sk, struct msghdr *msg, size_t size) {
    struct flow_event_t event = {};
    event.pid = bpf_get_current_pid_tgid() >> 32;
    event.bytes = size;
    event.ts_ns = bpf_ktime_get_ns();
    
    // Directly emits to user space ring buffer, inducing OOM during network microbursts
    bpf_ringbuf_output(&flow_events, &event, sizeof(event), 0);
    return 0;
}
```

#### Production Standard (Correct)
> **Standard**: Flow state is tracked inside kernel memory and governed by runtime backpressure parameters updated by the collector. Only anomalous flows (high latency, socket errors) or valid tail samples reach user space, preserving system stability and signal fidelity.
```c
// GOOD: Aggregates in an LRU map and conditionally emits via adaptive tail-sampling
SEC("kprobe/tcp_sendmsg")
int BPF_KPROBE(trace_tcp_sendmsg, struct sock *sk, struct msghdr *msg, size_t size) {
    u64 sk_key = (u64)sk;
    struct flow_state *state = bpf_map_lookup_elem(&active_flows, &sk_key);
    u64 now = bpf_ktime_get_ns();
    
    if (!state) {
        struct flow_state init = { .start_ns = now, .bytes = size, .is_anomalous = 0 };
        bpf_map_update_elem(&active_flows, &sk_key, &init, BPF_ANY);
        return 0;
    }
    
    state->bytes += size;
    u64 duration = now - state->start_ns;
    
    // Read real-time backpressure governor signaled by user-space collector
    u32 zero = 0;
    struct governor_cfg *cfg = bpf_map_lookup_elem(&governor_control, &zero);
    u32 sample_rate = (cfg && cfg->shed_nominal) ? cfg->nominal_rate_pct : 100;
    
    // Anomaly criteria: SLO breach, socket error, or random sampling pass
    if (duration > SLO_LATENCY_NS || BPF_CORE_READ(sk, sk_err) != 0) {
        state->is_anomalous = 1;
    }
    
    // Defer user-space ringbuf submission: only emit immediately if anomalous and unbuffered
    if (state->is_anomalous || (bpf_get_prandom_u32() % 100) < sample_rate) {
        struct flow_event_t *event = bpf_ringbuf_reserve(&flow_events, sizeof(*event), 0);
        if (event) {
            event->duration_ns = duration;
            event->bytes = state->bytes;
            event->anomalous = state->is_anomalous;
            bpf_ringbuf_submit(event, 0);
        }
    }
    return 0;
}
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: OpenTelemetry eBPF Dynamic Flow Tail-Sampling Kernel Governor

OpenTelemetry eBPF Dynamic Flow Tail-Sampling Kernel Governor defines an industrial-grade behavioral standard for devops engineering. Enforces in-kernel ring-buffer backpressure and dynamic tail-sampling for high-cardinality eBPF network flow telemetry during microbursts. Prevents user-space collector out-of-memory (OOM) crashes by shedding deterministic, healthy flow events in kernel space while guaranteeing 100% trace extraction for anomalous, high-latency, or errored socket transactions. 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 Head-Sampling Ring Buffer Emission Leading to Collector Node OOM 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 Head-Sampling Ring Buffer Emission Leading to Collector Node OOMCritical
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 implement local BPF hash maps (e.g., BPF_MAP_TYPE_HASH or BPF_MAP_TYPE_LRU_HASH) to hold active socket state until a transaction terminates or exceeds an anomaly threshold.

Engineers MUST ALWAYS implement local BPF hash maps (e.g., BPF_MAP_TYPE_HASH or BPF_MAP_TYPE_LRU_HASH) to hold active socket state until a transaction terminates or exceeds an anomaly threshold.

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 forward raw TCP packet headers directly to user space via BPF_MAP_TYPE_PERF_EVENT_ARRAY or BPF_MAP_TYPE_RINGBUF prior to classification.

Engineers MUST NOT forward raw TCP packet headers directly to user space via BPF_MAP_TYPE_PERF_EVENT_ARRAY or BPF_MAP_TYPE_RINGBUF prior to classification.

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

Kernels MUST dynamically apply an adaptive token bucket governor that downsamples nominal HTTP 200 / TCP FIN flows when collector consumer queue depth breaches the high-watermark threshold (>= 80%).

Kernels MUST dynamically apply an adaptive token bucket governor that downsamples nominal HTTP 200 / TCP FIN flows when collector consumer queue depth breaches the high-watermark threshold (>= 80%).

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

Services MUST guarantee deterministic delivery of telemetry frames tagged with TCP retransmissions (TCP_CA_Loss), socket-level errors (sk_err != 0), or latencies exceeding service-level SLO thresholds.

Services MUST guarantee deterministic delivery of telemetry frames tagged with TCP retransmissions (TCP_CA_Loss), socket-level errors (sk_err != 0), or latencies exceeding service-level SLO thresholds.

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

Collectors MUST expose a shared memory or atomic state flag (via BPF_MAP_TYPE_ARRAY) communicating user-space heap pressure back to the in-kernel filter for real-time backpressure.

Collectors MUST expose a shared memory or atomic state flag (via BPF_MAP_TYPE_ARRAY) communicating user-space heap pressure back to the in-kernel filter for real-time backpressure.

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 Dynamic Flow Tail-Sampling Kernel Governor critical for AI coding assistants?

Enforces in-kernel ring-buffer backpressure and dynamic tail-sampling for high-cardinality eBPF network flow telemetry during microbursts. Prevents user-space collector out-of-memory (OOM) crashes by shedding deterministic, healthy flow events in kernel space while guaranteeing 100% trace extraction for anomalous, high-latency, or errored socket transactions. 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 Head-Sampling Ring Buffer Emission Leading to Collector Node OOM) 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