This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
devopscritical PriorityID: ebpf-continuous-profiler-kernel-memory-budgeting-invariant

eBPF Continuous Profiler Kernel Memory Budgeting and Backpressure Invariant

Enforces deterministic, non-expandable kernel memory ceilings for continuous eBPF stack unwinding and ring buffer telemetry to eliminate kernel starvation during high-frequency burst events. Mandates explicit allocation sizing of BPF maps (BPF_MAP_TYPE_RINGBUF and BPF_MAP_TYPE_STACK_TRACE), hard pre-allocation without runtime growth, and kernel-side drop accounting instead of userspace unbounded queue accumulation.

Prohibited Anti-Pattern: Unbounded BPF Map Sizing and Ring-Buffer Channel Saturation Inducing Kernel OOM Panic

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: eBPF Continuous Profiler Kernel Memory Budgeting and Backpressure Invariant - Enforces deterministic, non-expandable kernel memory ceilings for continuous eBPF stack unwinding and ring buffer telemetry to eliminate kernel starvation during high-frequency burst events. Mandates explicit allocation sizing of BPF maps (BPF_MAP_TYPE_RINGBUF and BPF_MAP_TYPE_STACK_TRACE), hard pre-allocation without runtime growth, and kernel-side drop accounting instead of userspace unbounded queue accumulation.
globs: src/profiler/**/*.c, src/profiler/**/*.bpf.c, src/profiler/**/*.ts, src/profiler/**/*.go, packaging/k8s/**/*.yaml
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/ebpf-continuous-profiler-kernel-memory-budgeting-invariant"
---

# eBPF Continuous Profiler Kernel Memory Budgeting and Backpressure Invariant

> **Severity**: CRITICAL | **Category**: devops
> **Anti-Pattern Warning**: Unbounded BPF Map Sizing and Ring-Buffer Channel Saturation Inducing Kernel OOM Panic

## System Constraints
You are a Principal Systems Engineer enforcing strict host-level kernel memory budgeting for continuous eBPF telemetry and native/interpreter frame unwinding. You must prevent memory exhaustion, unbound dynamic map resizing, and OOM killer panics by mandating statically budgeted BPF ring buffers, pre-allocated stack-trace maps, page-aligned power-of-two buffer sizes, and userspace draining backpressure with drop counters.

## Strict Guidelines
- Engineers MUST ALWAYS enforce strict power-of-two page-aligned limits (`max_entries = 1 << N`) on `BPF_MAP_TYPE_RINGBUF` and ensure total profiler BPF memory does not exceed a hard host threshold (default: ≤64 MiB across all CPU cores).
- Engineers MUST ALWAYS initialize stack trace storage maps with `BPF_F_NO_PREALLOC` EXCLUSIVELY when memory footprint is verified at probe initialization; otherwise, pre-allocate maps explicitly to prevent allocation in page fault/NMI contexts.
- Engineers MUST NOT dynamically resize BPF maps or allow userspace agents to allocate unbound in-memory queues when the kernel ring buffer is drained faster than serialization handles.
- Code SHOULD implement atomic drop counters (`bpf_ringbuf_reserve` failure branch) in BPF programs to signal backpressure metrics to userspace without stalling unwinding loops.
- Services MUST verify `RLIMIT_MEMLOCK` or cgroup memory limit availability prior to loading BPF programs, gracefully failing or downsampling collection rates if memory headroom is insufficient.
- Components NEVER fall back to heap-allocating userspace buffers during ring-buffer drain storms; profiler ingestion MUST discard samples with telemetry export rather than exhaust system RAM.

## Bad vs Good Implementations
### Configuring BPF Ring Buffer & Profiler Agent Memory Ceiling

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Arbitrary buffer sizes violate kernel page alignment rules (causing load failures or excess slab wastage). The userspace consumer uses an unbounded array (`sampleQueue`) to ingest samples, which causes userspace OOM when high CPU load spikes sample rates beyond export throughput.
```typescript
// BAD: Arbitrary buffer sizing without page alignment, dynamic heap queueing in userspace,
// and no memory ceiling enforcement, triggering host OOM during CPU spikes.
import { EventEmitter } from 'events';

interface ProfilerConfig {
  ringBufferSize: number;
  unwindMapEntries: number;
}

export class ContinuousProfilerAgent extends EventEmitter {
  private config: ProfilerConfig;
  private sampleQueue: Array<Buffer> = []; // Unbounded heap accumulation

  constructor(config: ProfilerConfig) {
    super();
    this.config = config; // Uses dynamic/arbitrary sizes (e.g. 50_000_000 bytes)
  }

  public onSampleReceived(rawSample: Buffer): void {
    // Appends infinitely without inspecting memory limits or dropping
    this.sampleQueue.push(rawSample);
  }

  public loadBpfMaps(): { ringBufBytes: number; stackEntries: number } {
    return {
      ringBufBytes: this.config.ringBufferSize,
      stackEntries: this.config.unwindMapEntries,
    };
  }
}
```

#### Production Standard (Correct)
> **Standard**: Validates the power-of-two page-alignment invariant mandated by the BPF ring buffer subsystem, validates cumulative memory consumption against a hard host-level ceiling (64 MiB), and guarantees bounded userspace memory usage via drop-counters and bounded queues.
```typescript
// GOOD: Page-aligned power-of-two allocation, static kernel memory ceiling budget,
// and bounded userspace ring with explicit drop counters under backpressure.
import { EventEmitter } from 'events';

const PAGE_SIZE_BYTES = 4096;
const MAX_HOST_PROFILER_MEM_CEILING_BYTES = 64 * 1024 * 1024; // 64 MiB invariant

interface SafeProfilerBudget {
  ringBufBytes: number;
  stackMapEntries: number;
  approximateKernelUsageBytes: number;
}

export class ContinuousProfilerAgent extends EventEmitter {
  private readonly ringBufBytes: number;
  private readonly stackMapEntries: number;
  private droppedSamplesCount: number = 0;
  private readonly maxQueueDepth: number = 8192;
  private sampleQueue: Array<Buffer> = [];

  constructor(requestedRingBufBytes: number, stackMapEntries: number) {
    super();
    // Force ring buffer to be a power of two multiple of page size
    const alignedRingBuf = this.normalizePowerOfTwoPages(requestedRingBufBytes);
    const estimatedMapMemory = alignedRingBuf + (stackMapEntries * 128); // 128 bytes/stack entry average

    if (estimatedMapMemory > MAX_HOST_PROFILER_MEM_CEILING_BYTES) {
      throw new Error(
        `Requested profiler budget (${estimatedMapMemory} bytes) exceeds hard kernel ceiling (${MAX_HOST_PROFILER_MEM_CEILING_BYTES} bytes)`
      );
    }

    this.ringBufBytes = alignedRingBuf;
    this.stackMapEntries = stackMapEntries;
  }

  private normalizePowerOfTwoPages(bytes: number): number {
    let size = PAGE_SIZE_BYTES;
    while (size < bytes) {
      size <<= 1;
    }
    return size;
  }

  public onSampleReceived(rawSample: Buffer): void {
    if (this.sampleQueue.length >= this.maxQueueDepth) {
      this.droppedSamplesCount++;
      this.emit('backpressure:dropped', { totalDropped: this.droppedSamplesCount });
      return;
    }
    this.sampleQueue.push(rawSample);
  }

  public getBudgetPlan(): SafeProfilerBudget {
    return {
      ringBufBytes: this.ringBufBytes,
      stackMapEntries: this.stackMapEntries,
      approximateKernelUsageBytes: this.ringBufBytes + (this.stackMapEntries * 128),
    };
  }
}
```

Recommended MCP Servers (mcp-serverlist.com)

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

Recommended Agent Skills (askills.dev)

Ready-to-use executable skill functions tailored to this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: eBPF Continuous Profiler Kernel Memory Budgeting and Backpressure Invariant

eBPF Continuous Profiler Kernel Memory Budgeting and Backpressure Invariant defines an industrial-grade behavioral standard for devops engineering. Enforces deterministic, non-expandable kernel memory ceilings for continuous eBPF stack unwinding and ring buffer telemetry to eliminate kernel starvation during high-frequency burst events. Mandates explicit allocation sizing of BPF maps (BPF_MAP_TYPE_RINGBUF and BPF_MAP_TYPE_STACK_TRACE), hard pre-allocation without runtime growth, and kernel-side drop accounting instead of userspace unbounded queue accumulation. 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 BPF Map Sizing and Ring-Buffer Channel Saturation Inducing Kernel OOM Panic 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 BPF Map Sizing and Ring-Buffer Channel Saturation Inducing Kernel OOM PanicCritical
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 enforce strict power-of-two page-aligned limits (`max_entries = 1 << N`) on `BPF_MAP_TYPE_RINGBUF` and ensure total profiler BPF memory does not exceed a hard host threshold (default

Engineers MUST ALWAYS enforce strict power-of-two page-aligned limits (`max_entries = 1 << N`) on `BPF_MAP_TYPE_RINGBUF` and ensure total profiler BPF memory does not exceed a hard host threshold (default: ≤64 MiB across all CPU cores).

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 ALWAYS initialize stack trace storage maps with `BPF_F_NO_PREALLOC` EXCLUSIVELY when memory footprint is verified at probe initialization

Engineers MUST ALWAYS initialize stack trace storage maps with `BPF_F_NO_PREALLOC` EXCLUSIVELY when memory footprint is verified at probe initialization; otherwise, pre-allocate maps explicitly to prevent allocation in page fault/NMI contexts.

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

Engineers MUST NOT dynamically resize BPF maps or allow userspace agents to allocate unbound in-memory queues when the kernel ring buffer is drained faster than serialization handles.

Engineers MUST NOT dynamically resize BPF maps or allow userspace agents to allocate unbound in-memory queues when the kernel ring buffer is drained faster than serialization handles.

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

Code SHOULD implement atomic drop counters (`bpf_ringbuf_reserve` failure branch) in BPF programs to signal backpressure metrics to userspace without stalling unwinding loops.

Code SHOULD implement atomic drop counters (`bpf_ringbuf_reserve` failure branch) in BPF programs to signal backpressure metrics to userspace without stalling unwinding loops.

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

Services MUST verify `RLIMIT_MEMLOCK` or cgroup memory limit availability prior to loading BPF programs, gracefully failing or downsampling collection rates if memory headroom is insufficient.

Services MUST verify `RLIMIT_MEMLOCK` or cgroup memory limit availability prior to loading BPF programs, gracefully failing or downsampling collection rates if memory headroom is insufficient.

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

Components NEVER fall back to heap-allocating userspace buffers during ring-buffer drain storms

Components NEVER fall back to heap-allocating userspace buffers during ring-buffer drain storms; profiler ingestion MUST discard samples with telemetry export rather than exhaust system RAM.

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 eBPF Continuous Profiler Kernel Memory Budgeting and Backpressure Invariant critical for AI coding assistants?

Enforces deterministic, non-expandable kernel memory ceilings for continuous eBPF stack unwinding and ring buffer telemetry to eliminate kernel starvation during high-frequency burst events. Mandates explicit allocation sizing of BPF maps (BPF_MAP_TYPE_RINGBUF and BPF_MAP_TYPE_STACK_TRACE), hard pre-allocation without runtime growth, and kernel-side drop accounting instead of userspace unbounded queue accumulation. 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 BPF Map Sizing and Ring-Buffer Channel Saturation Inducing Kernel OOM Panic) 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

eBPF