This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: bun-cgroup-v2-memory-pressure-gc-sync

Bun 1.2 cgroup v2 Memory-Pressure GC Synchronization Guardrail

Enforces active synchronization between Linux cgroup v2 memory.events / memory.high signals and Bun's underlying JavaScriptCore garbage collector. Containers deployed in dense orchestration platforms risk sudden SIGKILL termination without active GC triggering because JavaScriptCore's default allocation heuristics are unaware of kernel cgroup boundaries.

Prohibited Anti-Pattern: Relying on Default JSC Heap Growth Inside Memory-Constrained Linux Containers

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 cgroup v2 Memory-Pressure GC Synchronization Guardrail - Enforces active synchronization between Linux cgroup v2 memory.events / memory.high signals and Bun's underlying JavaScriptCore garbage collector. Containers deployed in dense orchestration platforms risk sudden SIGKILL termination without active GC triggering because JavaScriptCore's default allocation heuristics are unaware of kernel cgroup boundaries.
globs: src/**/*.{ts,tsx}, infra/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-cgroup-v2-memory-pressure-gc-sync"
---

# Bun 1.2 cgroup v2 Memory-Pressure GC Synchronization Guardrail

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Relying on Default JSC Heap Growth Inside Memory-Constrained Linux Containers

## System Constraints
You are a Principal Backend and Systems Reliability Architect enforcing Bun 1.2 cgroup v2 memory boundary synchronization. You must ensure all containerized Bun microservices monitor cgroup v2 memory thresholds (memory.current, memory.high, and memory.events) and invoke Bun.gc(true) proactively before the Linux Out-Of-Memory (OOM) killer dispatches SIGKILL.

## Strict Guidelines
- Engineers MUST ALWAYS monitor `/sys/fs/cgroup/memory.events` or poll `/sys/fs/cgroup/memory.current` relative to `/sys/fs/cgroup/memory.max` (or `memory.high`) in long-running containerized Bun workloads.
- Engineers MUST invoke synchronous garbage collection via `Bun.gc(true)` whenever memory consumption crosses a predefined safety envelope (e.g., >= 80% of `memory.high` or `memory.max`).
- Engineers MUST NOT rely on autonomous JavaScriptCore GC triggers alone when deploying Bun into high-density Kubernetes pods or ECS tasks with tight memory limits.
- Services MUST implement exponential backoff and debouncing on forced GC passes to prevent synchronous GC lockup storms when memory remains persistently close to thresholds.
- Services MUST gracefully shed inbound load (e.g., return HTTP 503 or pause consumer loops) if a forced `Bun.gc(true)` cycle fails to reclaim memory below the critical pressure threshold.

## Bad vs Good Implementations
### cgroup v2 Pressure Monitor with Synchronous Bun GC Throttling

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: JavaScriptCore in Bun 1.2 defaults to host-level memory sizing if cgroups are unmonitored. Under concurrent allocations, memory reaches the container's hard limit (`memory.max`) before JSC's internal pressure heuristics fire, causing instantaneous container death without telemetry or graceful termination.
```typescript
import { serve } from 'bun';

// ANTI-PATTERN: Completely unmonitored memory lifecycle.
// JavaScriptCore expands heap based on host physical RAM, ignoring container cgroup quotas.
// Under peak load, Linux cgroup OOM killer sends SIGKILL (exit code 137) before JSC triggers full GC.
serve({
  port: 3000,
  async fetch(req) {
    const payload = await req.arrayBuffer();
    const transformed = Buffer.from(payload).reverse();
    return new Response(transformed);
  },
});
```

#### Production Standard (Correct)
> **Standard**: Reads the actual Linux cgroup v2 bounds (`memory.max` and `memory.current`). When allocations reach 80% capacity, it debounces and executes `Bun.gc(true)` to trigger a synchronous JSC sweep, avoiding the OOM killer. If memory remains critical (>= 90%), it sheds load with an HTTP 503 rather than crashing the container.
```typescript
import { serve } from 'bun';
import { readFileSync, existsSync } from 'node:fs';

class CgroupMemoryController {
  private static readonly CGROUP_BASE = '/sys/fs/cgroup';
  private static readonly HIGH_WATERMARK_RATIO = 0.80;
  private static readonly DEBOUNCE_MS = 2000;
  private lastGcTime = 0;
  private memoryLimit = Infinity;
  private isCgroupV2 = false;

  constructor() {
    const maxPath = `${CgroupMemoryController.CGROUP_BASE}/memory.max`;
    if (existsSync(maxPath)) {
      this.isCgroupV2 = true;
      const rawMax = readFileSync(maxPath, 'utf-8').trim();
      this.memoryLimit = rawMax === 'max' ? Infinity : Number(rawMax);
    }
  }

  public checkPressureAndReclaim(): boolean {
    if (!this.isCgroupV2 || !Number.isFinite(this.memoryLimit)) return false;

    const current = Number(readFileSync(`${CgroupMemoryController.CGROUP_BASE}/memory.current`, 'utf-8').trim());
    const utilization = current / this.memoryLimit;

    if (utilization >= CgroupMemoryController.HIGH_WATERMARK_RATIO) {
      const now = Date.now();
      if (now - this.lastGcTime > CgroupMemoryController.DEBOUNCE_MS) {
        // Synchronous JavaScriptCore GC sweep to immediately reclaim unreferenced buffers
        Bun.gc(true);
        this.lastGcTime = now;
        
        const postCurrent = Number(readFileSync(`${CgroupMemoryController.CGROUP_BASE}/memory.current`, 'utf-8').trim());
        return (postCurrent / this.memoryLimit) >= 0.90;
      }
    }
    return false;
  }
}

const memoryGuard = new CgroupMemoryController();

serve({
  port: 3000,
  async fetch(req) {
    const isCriticallyPressured = memoryGuard.checkPressureAndReclaim();
    if (isCriticallyPressured) {
      return new Response('System under critical memory pressure. Please retry.', { status: 503 });
    }

    const payload = await req.arrayBuffer();
    const transformed = Buffer.from(payload).reverse();
    return new Response(transformed);
  },
});
```

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: Bun 1.2 cgroup v2 Memory-Pressure GC Synchronization Guardrail

Bun 1.2 cgroup v2 Memory-Pressure GC Synchronization Guardrail defines an industrial-grade behavioral standard for backend engineering. Enforces active synchronization between Linux cgroup v2 memory.events / memory.high signals and Bun's underlying JavaScriptCore garbage collector. Containers deployed in dense orchestration platforms risk sudden SIGKILL termination without active GC triggering because JavaScriptCore's default allocation heuristics are unaware of kernel cgroup boundaries. 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: Relying on Default JSC Heap Growth Inside Memory-Constrained Linux Containers 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 DriftRelying on Default JSC Heap Growth Inside Memory-Constrained Linux ContainersCritical
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 monitor `/sys/fs/cgroup/memory.events` or poll `/sys/fs/cgroup/memory.current` relative to `/sys/fs/cgroup/memory.max` (or `memory.high`) in long-running containerized Bun workloads.

Engineers MUST ALWAYS monitor `/sys/fs/cgroup/memory.events` or poll `/sys/fs/cgroup/memory.current` relative to `/sys/fs/cgroup/memory.max` (or `memory.high`) in long-running containerized Bun workloads.

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 invoke synchronous garbage collection via `Bun.gc(true)` whenever memory consumption crosses a predefined safety envelope (e.g., >= 80% of `memory.high` or `memory.max`).

Engineers MUST invoke synchronous garbage collection via `Bun.gc(true)` whenever memory consumption crosses a predefined safety envelope (e.g., >= 80% of `memory.high` or `memory.max`).

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 rely on autonomous JavaScriptCore GC triggers alone when deploying Bun into high-density Kubernetes pods or ECS tasks with tight memory limits.

Engineers MUST NOT rely on autonomous JavaScriptCore GC triggers alone when deploying Bun into high-density Kubernetes pods or ECS tasks with tight memory limits.

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 implement exponential backoff and debouncing on forced GC passes to prevent synchronous GC lockup storms when memory remains persistently close to thresholds.

Services MUST implement exponential backoff and debouncing on forced GC passes to prevent synchronous GC lockup storms when memory remains persistently close to 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

Services MUST gracefully shed inbound load (e.g., return HTTP 503 or pause consumer loops) if a forced `Bun.gc(true)` cycle fails to reclaim memory below the critical pressure threshold.

Services MUST gracefully shed inbound load (e.g., return HTTP 503 or pause consumer loops) if a forced `Bun.gc(true)` cycle fails to reclaim memory below the critical pressure 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.
Technical Questions & Answers

Frequently Asked Technical Questions

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

Q:Why is Bun 1.2 cgroup v2 Memory-Pressure GC Synchronization Guardrail critical for AI coding assistants?

Enforces active synchronization between Linux cgroup v2 memory.events / memory.high signals and Bun's underlying JavaScriptCore garbage collector. Containers deployed in dense orchestration platforms risk sudden SIGKILL termination without active GC triggering because JavaScriptCore's default allocation heuristics are unaware of kernel cgroup boundaries. 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 (Relying on Default JSC Heap Growth Inside Memory-Constrained Linux Containers) 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

Bun