This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
devopscritical PriorityID: opentelemetry-batch-span-processor-memory-fence

OpenTelemetry BatchSpanProcessor Memory Bounding and Non-Blocking Buffer Fence

Enforces strict memory allocation fences on OpenTelemetry trace exporters via bounded ring buffers and aggressive drop-on-saturation policies. Prevents catastrophic process-level Out-Of-Memory (OOM) crashes during collector outages and telemetry bursts.

Prohibited Anti-Pattern: Unbounded Telemetry Queues and Indefinite Export Timeouts Triggering Fatal Heap Exhaustion

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenTelemetry BatchSpanProcessor Memory Bounding and Non-Blocking Buffer Fence - Enforces strict memory allocation fences on OpenTelemetry trace exporters via bounded ring buffers and aggressive drop-on-saturation policies. Prevents catastrophic process-level Out-Of-Memory (OOM) crashes during collector outages and telemetry bursts.
globs: src/**/tracing.{ts,js}, src/**/telemetry/**/*.{ts,js}, src/**/instrumentation.{ts,js}, src/**/otel*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/opentelemetry-batch-span-processor-memory-fence"
---

# OpenTelemetry BatchSpanProcessor Memory Bounding and Non-Blocking Buffer Fence

> **Severity**: CRITICAL | **Category**: devops
> **Anti-Pattern Warning**: Unbounded Telemetry Queues and Indefinite Export Timeouts Triggering Fatal Heap Exhaustion

## System Constraints
You are a Principal Telemetry and Site Reliability Architect enforcing deterministic memory limits for OpenTelemetry ingestion. You must prevent telemetry from causing host process crashes by enforcing non-blocking ring-buffer constraints, strict queue capacity ceilings, aggressive export timeouts, and explicit drop counters.

## Strict Guidelines
- Engineers MUST ALWAYS explicitly configure maxQueueSize, maxExportBatchSize, and exportTimeoutMillis when initializing BatchSpanProcessor.
- Engineers MUST NOT configure maxQueueSize greater than 2048 spans in Node.js production environments without dedicated heap profiling verification.
- Code MUST ensure maxExportBatchSize is less than or equal to half of maxQueueSize (maxExportBatchSize <= maxQueueSize / 2) to maintain drain throughput without starvation.
- Services MUST configure exportTimeoutMillis to a deterministic ceiling (maximum 5000ms) to ensure collector socket hangup does not preserve memory references in the process heap.
- Components NEVER block application runtime event loops on telemetry backpressure; buffers must drop oldest or reject incoming telemetry non-blockingly upon reaching max capacity.

## Bad vs Good Implementations
### Configuring Memory-Bounded BatchSpanProcessor with Drop Fencing

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Default BatchSpanProcessor configuration holds spans for up to 30,000ms with unbounded retry memory pressure. Under traffic spikes or collector unavailability, spans with associated attributes, events, and stack traces pile up indefinitely, triggering an OOM crash.
```typescript
import { NodeTracerProvider } from '@opentelemetry/sdk-trace-node';
import { BatchSpanProcessor } from '@opentelemetry/sdk-trace-base';
import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-grpc';

const provider = new NodeTracerProvider();

// ANTI-PATTERN: Default configurations permit large unbounded queues (up to 2048 by default,
// but with 30-second timeouts and high retention across async collectors). During network
// partition or collector degradation, un-evicted retained trace trees consume hundreds
// of megabytes, crashing the V8 engine with JavaScript heap out of memory.
const exporter = new OTLPTraceExporter();
provider.addSpanProcessor(new BatchSpanProcessor(exporter));
provider.register();
```

#### Production Standard (Correct)
> **Standard**: Enforces a rigid memory ceiling and short timeouts (3000ms). When the queue reaches capacity (2048 spans), new spans are dropped non-blockingly at the boundary without allocating heap, completely isolating application stability from observability downstream availability.
```typescript
import { NodeTracerProvider } from '@opentelemetry/sdk-trace-node';
import { BatchSpanProcessor, BufferConfig } from '@opentelemetry/sdk-trace-base';
import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-grpc';
import { diag } from '@opentelemetry/api';

const provider = new NodeTracerProvider();

// PRODUCTION INVARIANT: Hard-fenced ring buffer configuration
// maxQueueSize: Restricts absolute in-memory pending spans (2048 * ~2KB = ~4MB ceiling)
// maxExportBatchSize: Flushes in non-blocking slices (512)
// scheduledDelayMillis: Empties queue rapidly (1000ms)
// exportTimeoutMillis: Hard timeout fails fast on dead network (3000ms)
const bufferConfig: BufferConfig = {
  maxQueueSize: 2048,
  maxExportBatchSize: 512,
  scheduledDelayMillis: 1000,
  exportTimeoutMillis: 3000,
};

const exporter = new OTLPTraceExporter({
  timeoutMillis: 3000,
});

const processor = new BatchSpanProcessor(exporter, bufferConfig);
provider.addSpanProcessor(processor);
provider.register();

diag.info('Telemetry initialized with hard memory-fenced BatchSpanProcessor');
```

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: OpenTelemetry BatchSpanProcessor Memory Bounding and Non-Blocking Buffer Fence

OpenTelemetry BatchSpanProcessor Memory Bounding and Non-Blocking Buffer Fence defines an industrial-grade behavioral standard for devops engineering. Enforces strict memory allocation fences on OpenTelemetry trace exporters via bounded ring buffers and aggressive drop-on-saturation policies. Prevents catastrophic process-level Out-Of-Memory (OOM) crashes during collector outages and telemetry bursts. 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 Telemetry Queues and Indefinite Export Timeouts Triggering Fatal Heap Exhaustion 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 Telemetry Queues and Indefinite Export Timeouts Triggering Fatal Heap ExhaustionCritical
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 explicitly configure maxQueueSize, maxExportBatchSize, and exportTimeoutMillis when initializing BatchSpanProcessor.

Engineers MUST ALWAYS explicitly configure maxQueueSize, maxExportBatchSize, and exportTimeoutMillis when initializing BatchSpanProcessor.

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 configure maxQueueSize greater than 2048 spans in Node.js production environments without dedicated heap profiling verification.

Engineers MUST NOT configure maxQueueSize greater than 2048 spans in Node.js production environments without dedicated heap profiling verification.

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

Code MUST ensure maxExportBatchSize is less than or equal to half of maxQueueSize (maxExportBatchSize <= maxQueueSize / 2) to maintain drain throughput without starvation.

Code MUST ensure maxExportBatchSize is less than or equal to half of maxQueueSize (maxExportBatchSize <= maxQueueSize / 2) to maintain drain throughput without starvation.

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 configure exportTimeoutMillis to a deterministic ceiling (maximum 5000ms) to ensure collector socket hangup does not preserve memory references in the process heap.

Services MUST configure exportTimeoutMillis to a deterministic ceiling (maximum 5000ms) to ensure collector socket hangup does not preserve memory references in the process heap.

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

Components NEVER block application runtime event loops on telemetry backpressure

Components NEVER block application runtime event loops on telemetry backpressure; buffers must drop oldest or reject incoming telemetry non-blockingly upon reaching max capacity.

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 BatchSpanProcessor Memory Bounding and Non-Blocking Buffer Fence critical for AI coding assistants?

Enforces strict memory allocation fences on OpenTelemetry trace exporters via bounded ring buffers and aggressive drop-on-saturation policies. Prevents catastrophic process-level Out-Of-Memory (OOM) crashes during collector outages and telemetry bursts. 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 Telemetry Queues and Indefinite Export Timeouts Triggering Fatal Heap Exhaustion) 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