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

Capacitor 7 Native Background Runner Execution Budget Standard

Enforces strict OS battery, thermal state, and wall-clock execution quotas on Capacitor 7 Native Background Runner routines. Prevents unnotified mobile OS process termination (iOS 0x8badf00d watchdog kills and Android WorkManager battery-saver evictions) via pre-flight hardware checks, bounded AbortSignal timeouts, and idempotent state checkpointing.

Prohibited Anti-Pattern: Unbounded Background Runner Dispatches Lacking Battery, Thermal, and Execution Watchdog Guardrails

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 Native Background Runner Execution Budget Standard - Enforces strict OS battery, thermal state, and wall-clock execution quotas on Capacitor 7 Native Background Runner routines. Prevents unnotified mobile OS process termination (iOS 0x8badf00d watchdog kills and Android WorkManager battery-saver evictions) via pre-flight hardware checks, bounded AbortSignal timeouts, and idempotent state checkpointing.
globs: src/**/background/**/*.{ts,js}, src/**/tasks/**/*.{ts,js}, src/**/workers/**/*.{ts,js}, capacitor.config.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor-7-background-runner-budget-standard"
---

# Capacitor 7 Native Background Runner Execution Budget Standard

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Unbounded Background Runner Dispatches Lacking Battery, Thermal, and Execution Watchdog Guardrails

## System Constraints
You are a Principal Mobile Architect enforcing the Capacitor 7 Native Background Runner Execution Budget Standard. Capacitor 7 executes background tasks in an isolated JavaScript runner context backed by iOS BackgroundTasks (BGAppRefreshTask/BGProcessingTask) and Android WorkManager. Unbounded background cycles lead to silent OS termination, battery drain penalties, and application suspension. You must reject any background runner implementation that executes unbounded loops, fails to check battery level and thermal state before dispatching tasks, or exceeds bounded OS execution limits (maximum 20-25 seconds for app refresh tasks). Mandate proactive cancellation tokens (AbortController), atomic checkpointing, and dynamic throttling when the device is under thermal duress or low power mode.

## Strict Guidelines
- Engineers MUST ALWAYS implement a pre-flight quota inspection (battery level, charging status, and thermal state) before executing sync workloads in Background Runner handlers.
- Engineers MUST ALWAYS wrap Background Runner network and compute routines in an AbortController with a hard deadline <= 20,000ms to stay safely below the iOS 30-second watchdog limit.
- Engineers MUST NOT dispatch non-critical analytical or heavy computational sync payloads when the OS reports Low Power Mode / Battery Saver or serious/critical thermal throttling.
- Code SHOULD persist state checkpoints atomically after each processed batch item so interrupted tasks can resume idempotently without duplicating side effects.
- Services MUST gracefully release resources and notify the native runtime via runner resolution or rejection before the OS hard termination threshold is reached.
- Components NEVER trigger continuous setInterval or unmetered recursive loops within Capacitor background runner scripts.

## Bad vs Good Implementations
### Capacitor 7 Background Runner Task Registration with Execution Budget Guard

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Fails to inspect battery percentage, charging state, or thermal status before initiating network requests. Lacks an AbortController or execution deadline; if network latency spikes or the record set is large, iOS will terminate the process with SIGKILL (0x8badf00d) and Android will flag the app for excessive battery drain.
```typescript
import { BackgroundRunner } from '@capacitor/background-runner';

// ANTI-PATTERN: Unbounded execution without battery checks or abort timeouts
addEventListener('syncDataTask', async (resolve, reject, args) => {
  try {
    const pendingItems = await fetchPendingDatabaseRecords();
    
    // Unbounded sequential processing can easily exceed OS 30-second budget
    for (const item of pendingItems) {
      await fetch('https://api.example.com/sync', {
        method: 'POST',
        body: JSON.stringify(item)
      });
      await markItemSynced(item.id);
    }
    
    resolve({ status: 'completed' });
  } catch (error) {
    reject(error);
  }
});
```

#### Production Standard (Correct)
> **Standard**: Implements pre-flight hardware checks using Device.getBatteryInfo to prevent background draining under battery duress. Enforces a strict 20,000ms budget with AbortController, ensuring each network call is abortable and preventing 0x8badf00d kills while atomically checkpointing synced state.
```typescript
import { Device } from '@capacitor/device';

interface SyncPayload {
  id: string;
  data: Record<string, unknown>;
}

// Bound execution to 20 seconds max (safe margin for iOS 30s background budget)
const BACKGROUND_EXECUTION_BUDGET_MS = 20000;
const CRITICAL_BATTERY_THRESHOLD = 0.15;

addEventListener('syncDataTask', async (resolve, reject, args) => {
  const abortController = new AbortController();
  const timeoutHandle = setTimeout(() => {
    abortController.abort(new Error('EXECUTION_BUDGET_EXCEEDED'));
  }, BACKGROUND_EXECUTION_BUDGET_MS);

  try {
    // 1. Pre-flight Hardware & Quota Checks
    const batteryInfo = await Device.getBatteryInfo();
    if (!batteryInfo.isCharging && batteryInfo.batteryLevel !== undefined && batteryInfo.batteryLevel < CRITICAL_BATTERY_THRESHOLD) {
      clearTimeout(timeoutHandle);
      resolve({ status: 'deferred_low_battery', processed: 0 });
      return;
    }

    const pendingRecords: SyncPayload[] = await fetchPendingDatabaseRecords();
    let processedCount = 0;

    // 2. Metered execution with cancellation checkpointing
    for (const record of pendingRecords) {
      if (abortController.signal.aborted) {
        break;
      }

      const response = await fetch('https://api.example.com/sync', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(record),
        signal: abortController.signal
      });

      if (!response.ok) {
        throw new Error(`Sync failed with HTTP ${response.status}`);
      }

      await markItemSynced(record.id);
      processedCount++;
    }

    clearTimeout(timeoutHandle);
    resolve({ 
      status: abortController.signal.aborted ? 'partially_completed' : 'completed', 
      processed: processedCount 
    });
  } catch (error: any) {
    clearTimeout(timeoutHandle);
    if (error?.name === 'AbortError' || error?.message === 'EXECUTION_BUDGET_EXCEEDED') {
      resolve({ status: 'budget_exhausted_graceful_exit' });
    } else {
      reject(error);
    }
  }
});
```

Recommended MCP Servers (mcp-serverlist.com)

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

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Capacitor 7 Native Background Runner Execution Budget Standard

Capacitor 7 Native Background Runner Execution Budget Standard defines an industrial-grade behavioral standard for mobile engineering. Enforces strict OS battery, thermal state, and wall-clock execution quotas on Capacitor 7 Native Background Runner routines. Prevents unnotified mobile OS process termination (iOS 0x8badf00d watchdog kills and Android WorkManager battery-saver evictions) via pre-flight hardware checks, bounded AbortSignal timeouts, and idempotent state checkpointing. 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 Background Runner Dispatches Lacking Battery, Thermal, and Execution Watchdog Guardrails 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 Background Runner Dispatches Lacking Battery, Thermal, and Execution Watchdog GuardrailsCritical
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 a pre-flight quota inspection (battery level, charging status, and thermal state) before executing sync workloads in Background Runner handlers.

Engineers MUST ALWAYS implement a pre-flight quota inspection (battery level, charging status, and thermal state) before executing sync workloads in Background Runner handlers.

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 wrap Background Runner network and compute routines in an AbortController with a hard deadline <= 20,000ms to stay safely below the iOS 30-second watchdog limit.

Engineers MUST ALWAYS wrap Background Runner network and compute routines in an AbortController with a hard deadline <= 20,000ms to stay safely below the iOS 30-second watchdog limit.

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 dispatch non-critical analytical or heavy computational sync payloads when the OS reports Low Power Mode / Battery Saver or serious/critical thermal throttling.

Engineers MUST NOT dispatch non-critical analytical or heavy computational sync payloads when the OS reports Low Power Mode / Battery Saver or serious/critical thermal throttling.

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 persist state checkpoints atomically after each processed batch item so interrupted tasks can resume idempotently without duplicating side effects.

Code SHOULD persist state checkpoints atomically after each processed batch item so interrupted tasks can resume idempotently without duplicating side effects.

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 release resources and notify the native runtime via runner resolution or rejection before the OS hard termination threshold is reached.

Services MUST gracefully release resources and notify the native runtime via runner resolution or rejection before the OS hard termination threshold is reached.

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 trigger continuous setInterval or unmetered recursive loops within Capacitor background runner scripts.

Components NEVER trigger continuous setInterval or unmetered recursive loops within Capacitor background runner scripts.

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 Native Background Runner Execution Budget Standard critical for AI coding assistants?

Enforces strict OS battery, thermal state, and wall-clock execution quotas on Capacitor 7 Native Background Runner routines. Prevents unnotified mobile OS process termination (iOS 0x8badf00d watchdog kills and Android WorkManager battery-saver evictions) via pre-flight hardware checks, bounded AbortSignal timeouts, and idempotent state checkpointing. 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 Background Runner Dispatches Lacking Battery, Thermal, and Execution Watchdog Guardrails) 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