This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: capacitor-7-background-runner-memory-fence-standard

Capacitor 7 Background Runner Memory-Fence and Task Lifecycle Architecture

Establishes non-blocking memory fences and strict execution-window boundaries for @capacitor/background-runner tasks on iOS and Android runtimes. Preempts unnotified operating system SIGKILL and OOM events by constraining background heap allocation, isolating native IPC payloads, and mandating explicit cooperative multitasking checkpoints within the isolated JavaScript execution context.

Prohibited Anti-Pattern: Unbounded Heap Accumulation and Hanging Event Loops in Capacitor Background Runner Contexts

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 Background Runner Memory-Fence and Task Lifecycle Architecture - Establishes non-blocking memory fences and strict execution-window boundaries for @capacitor/background-runner tasks on iOS and Android runtimes. Preempts unnotified operating system SIGKILL and OOM events by constraining background heap allocation, isolating native IPC payloads, and mandating explicit cooperative multitasking checkpoints within the isolated JavaScript execution context.
globs: capacitor.config.ts, src/workers/**/*.{js,ts}, src/background/**/*.{js,ts}, src/services/background/**/*.{js,ts}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor-7-background-runner-memory-fence-standard"
---

# Capacitor 7 Background Runner Memory-Fence and Task Lifecycle Architecture

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Unbounded Heap Accumulation and Hanging Event Loops in Capacitor Background Runner Contexts

## System Constraints
You are a Principal Mobile Architect enforcing the Capacitor 7 Background Runner Web Worker Memory-Fence Standard. You must reject any background runner implementation that allows unbounded in-memory collection buffering, long-running un-yielded promises, omission of explicit task termination signals, or reliance on full DOM/BOM APIs inside isolated background JavaScript runtimes. Enforce strict memory fences, structured stream processing, and defensive native dispatching.

## Strict Guidelines
- Engineers MUST ALWAYS invoke native background completion hooks (`CapacitorKV` sync / return value resolution) before the OS deadline expires (typically <= 25 seconds on iOS BGTaskScheduler).
- Engineers MUST NOT allocate unbounded arrays or parse monolithic JSON payloads exceeding 2MB inside the Background Runner context to avoid immediate kernel OOM termination.
- Code SHOULD enforce chunked streaming architectures and manual garbage-collection hints (nullifying references and scoping iterations) within background task functions.
- Services MUST isolate the background runner entry script from main web application bundles, avoiding DOM dependencies, UI stores, and window-dependent web APIs.
- Components NEVER trigger synchronous blocking computational loops inside background event handlers without yielding back to the microtask queue via cooperative delays.

## Bad vs Good Implementations
### Memory-Unbounded Background Sync vs Chunked Memory-Fenced Worker Execution

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Parsing massive JSON bodies inside the background runtime causes instant heap spikes. The Background Runner operates in a restricted V8/JSC environment where memory allocations above 15-30MB trigger uncatchable OS process terminations without logging or cleanup.
```typescript
import { BackgroundRunner } from '@capacitor/background-runner';

// ANTI-PATTERN: Loading entire remote batch into worker memory,
// keeping heavy object graphs active without lifecycle yield,
// and ignoring the strict iOS/Android OS background runtime ceiling.
addEventListener('syncBackgroundData', async (resolve, reject, args) => {
  try {
    const response = await fetch('https://api.example.com/bulk-telemetry');
    const fullPayload: Record<string, unknown>[] = await response.json(); // May allocate 20MB+
    
    const processed = fullPayload.map((item) => ({
      ...item,
      processedAt: Date.now(),
    }));

    // Retains massive payload in JS heap, risking silent native SIGKILL
    CapacitorKV.set('telemetry_cache', JSON.stringify(processed));
    resolve({ count: processed.length });
  } catch (err) {
    reject(err);
  }
});
```

#### Production Standard (Correct)
> **Standard**: The good pattern enforces a streaming memory fence, bounds heap allocation to tiny discrete batches, explicitly truncates array references to encourage immediate garbage collection, and enforces a strict 20-second time budget to resolve before the mobile OS terminates the process.
```typescript
import { BackgroundRunner } from '@capacitor/background-runner';

const BATCH_SIZE = 50;
const TIME_BUDGET_MS = 20_000; // Defensive ceiling under 25s iOS threshold

addEventListener('syncBackgroundData', async (resolve, reject, args) => {
  const startTime = Date.now();
  let processedCount = 0;

  try {
    const response = await fetch('https://api.example.com/bulk-telemetry-stream');
    if (!response.body) throw new Error('ReadableStream not supported');

    const reader = response.body.getReader();
    const decoder = new TextDecoder();
    let buffer = '';

    while (true) {
      // Cooperative lifecycle fence: prevent OS execution watchdog kill
      if (Date.now() - startTime > TIME_BUDGET_MS) {
        console.warn('MemoryFence: Yielding execution due to background time budget.');
        break;
      }

      const { done, value } = await reader.read();
      if (done) break;

      buffer += decoder.decode(value, { stream: true });
      const lines = buffer.split('\n');
      buffer = lines.pop() ?? ''; // Retain partial segment

      if (lines.length >= BATCH_SIZE) {
        // Process and immediately flush to persistent native storage
        CapacitorKV.set(`batch_${processedCount}`, JSON.stringify(lines));
        processedCount += lines.length;
        lines.length = 0; // Explicit reference release to permit GC
      }
    }

    // Explicitly resolve prior to native execution window cutoff
    resolve({ status: 'completed', processedCount });
  } catch (error) {
    reject(error instanceof Error ? error.message : 'Unknown background error');
  }
});
```

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: Capacitor 7 Background Runner Memory-Fence and Task Lifecycle Architecture

Capacitor 7 Background Runner Memory-Fence and Task Lifecycle Architecture defines an industrial-grade behavioral standard for mobile engineering. Establishes non-blocking memory fences and strict execution-window boundaries for @capacitor/background-runner tasks on iOS and Android runtimes. Preempts unnotified operating system SIGKILL and OOM events by constraining background heap allocation, isolating native IPC payloads, and mandating explicit cooperative multitasking checkpoints within the isolated JavaScript execution 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 Heap Accumulation and Hanging Event Loops in Capacitor Background Runner Contexts 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 Heap Accumulation and Hanging Event Loops in Capacitor Background Runner ContextsCritical
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 invoke native background completion hooks (`CapacitorKV` sync / return value resolution) before the OS deadline expires (typically <= 25 seconds on iOS BGTaskScheduler).

Engineers MUST ALWAYS invoke native background completion hooks (`CapacitorKV` sync / return value resolution) before the OS deadline expires (typically <= 25 seconds on iOS BGTaskScheduler).

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 allocate unbounded arrays or parse monolithic JSON payloads exceeding 2MB inside the Background Runner context to avoid immediate kernel OOM termination.

Engineers MUST NOT allocate unbounded arrays or parse monolithic JSON payloads exceeding 2MB inside the Background Runner context to avoid immediate kernel OOM termination.

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 SHOULD enforce chunked streaming architectures and manual garbage-collection hints (nullifying references and scoping iterations) within background task functions.

Code SHOULD enforce chunked streaming architectures and manual garbage-collection hints (nullifying references and scoping iterations) within background task functions.

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 isolate the background runner entry script from main web application bundles, avoiding DOM dependencies, UI stores, and window-dependent web APIs.

Services MUST isolate the background runner entry script from main web application bundles, avoiding DOM dependencies, UI stores, and window-dependent web APIs.

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 trigger synchronous blocking computational loops inside background event handlers without yielding back to the microtask queue via cooperative delays.

Components NEVER trigger synchronous blocking computational loops inside background event handlers without yielding back to the microtask queue via cooperative delays.

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 Capacitor 7 Background Runner Memory-Fence and Task Lifecycle Architecture critical for AI coding assistants?

Establishes non-blocking memory fences and strict execution-window boundaries for @capacitor/background-runner tasks on iOS and Android runtimes. Preempts unnotified operating system SIGKILL and OOM events by constraining background heap allocation, isolating native IPC payloads, and mandating explicit cooperative multitasking checkpoints within the isolated JavaScript execution 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 Heap Accumulation and Hanging Event Loops in Capacitor Background Runner Contexts) 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.

Related MOBILE Rules

View all rules →
1 Rule in Stack

Capacitor