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

Capacitor 7 Background Task Execution OS Power-Budget Quarantine

Enforces strict time-sliced execution budgets, thermal throttling, and atomic checkpointing for background jobs in Capacitor 7. Modern iOS (BGTaskScheduler) and Android (Doze/WorkManager) strictly enforce execution limits (~25-30s) and kill non-compliant runtimes without warning (0x8badf00d SIGKILL). This standard prevents silent background eviction by enforcing deterministic chunking and graceful task termination.

Prohibited Anti-Pattern: Unbounded Background Synchronization Causing Silent OS Watchdog SIGKILL and Battery Quota Depletion

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 Background Task Execution OS Power-Budget Quarantine - Enforces strict time-sliced execution budgets, thermal throttling, and atomic checkpointing for background jobs in Capacitor 7. Modern iOS (BGTaskScheduler) and Android (Doze/WorkManager) strictly enforce execution limits (~25-30s) and kill non-compliant runtimes without warning (0x8badf00d SIGKILL). This standard prevents silent background eviction by enforcing deterministic chunking and graceful task termination.
globs: src/**/*.{ts,tsx}, src/workers/**/*.{ts,js}, src/plugins/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor-7-background-task-os-budget-quarantine"
---

# Capacitor 7 Background Task Execution OS Power-Budget Quarantine

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Unbounded Background Synchronization Causing Silent OS Watchdog SIGKILL and Battery Quota Depletion

## System Constraints
You are a Principal Mobile Architect enforcing Capacitor 7 Background Task Execution OS Power-Budget Quarantine. Mandate strict execution budgets, bounded batch sizes, atomic checkpointing to persistent storage, and definitive cleanup callbacks to avoid iOS 0x8badf00d kills and Android App Standby Bucket quarantine.

## Strict Guidelines
- Engineers MUST ALWAYS enforce a hard execution budget cap of 20,000 milliseconds per background task to preserve an OS-required 5-10 second safety margin before native watchdog termination.
- Engineers MUST NOT run unbounded arrays, continuous polling loops, or non-deterministic recursive promises within background runner callbacks.
- Code SHOULD persist an atomic synchronization checkpoint (e.g., last processed cursor or sequence ID) after every individual atomic unit of work, allowing resumed execution in subsequent cycles.
- Services MUST invoke `BackgroundTask.finish({ taskId })` deterministically within a `finally` block or when reaching 80% of the elapsed time budget, whichever occurs first.
- Components NEVER execute raw HTTP downloads, large binary mutations, or non-critical analytics in foreground-transition background events; offload heavy jobs strictly to native WorkManager or BGProcessingTask bindings.

## Bad vs Good Implementations
### Unbounded Loop vs. Budget-Quarantined Chunked Background Worker

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Iterating over unbounded remote or local mutations without remaining-time checks exceeds the 30-second iOS Background App Refresh or background expiration window. When iOS watchdogs terminate the process via SIGKILL, unfinished I/O can corrupt databases and subsequent background execution slots are throttled by the OS.
```typescript
import { BackgroundTask } from '@capacitor/background-task';
import { syncPendingMutations } from './syncService';

export async function handleAppBackground() {
  const taskId = await BackgroundTask.beforeExit(async () => {
    // ANTI-PATTERN: Indefinite execution over unbounded dataset.
    // If dataset has 200 items and takes > 30s, iOS triggers SIGKILL (0x8badf00d)
    // with zero catchable exceptions, leaving local state corrupted.
    const pending = await getPendingMutations();
    for (const item of pending) {
      await syncPendingMutations(item);
    }
    BackgroundTask.finish({ taskId });
  });
}
```

#### Production Standard (Correct)
> **Standard**: Implements an OS-budget quarantine capped at 20,000ms, persists atomic checkpoints after each item, and ensures `BackgroundTask.finish({ taskId })` is always called in a `finally` block, preventing OS task starvation and SIGKILL termination.
```typescript
import { BackgroundTask } from '@capacitor/background-task';
import { Preferences } from '@capacitor/preferences';
import { syncPendingMutation, getPendingMutations } from './syncService';

const MAX_EXECUTION_MS = 20_000; // 20s budget: Leaves 10s buffer for OS cleanup
const CHECKPOINT_KEY = 'sync_checkpoint_cursor';

export async function handleAppBackground(): Promise<void> {
  let taskId: string | undefined;
  
  try {
    taskId = await BackgroundTask.beforeExit(async () => {
      const startTime = Date.now();
      const lastCursor = (await Preferences.get({ key: CHECKPOINT_KEY })).value;
      const pending = await getPendingMutations(lastCursor);

      for (const item of pending) {
        // Guardrail: Quarantine task execution against remaining OS budget
        const elapsed = Date.now() - startTime;
        if (elapsed >= MAX_EXECUTION_MS) {
          console.warn(`[BackgroundSync] Budget ceiling reached (${elapsed}ms). Yielding.`);
          break;
        }

        await syncPendingMutation(item);
        
        // Atomic checkpointing guarantees idempotent resumption
        await Preferences.set({ key: CHECKPOINT_KEY, value: item.id });
      }
    });
  } catch (error) {
    console.error('[BackgroundSync] Critical failure during background routine', error);
  } finally {
    if (taskId) {
      // Guardrail: MUST notify the OS immediately to prevent battery penalty
      BackgroundTask.finish({ taskId });
    }
  }
}
```

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 Background Task Execution OS Power-Budget Quarantine

Capacitor 7 Background Task Execution OS Power-Budget Quarantine defines an industrial-grade behavioral standard for mobile engineering. Enforces strict time-sliced execution budgets, thermal throttling, and atomic checkpointing for background jobs in Capacitor 7. Modern iOS (BGTaskScheduler) and Android (Doze/WorkManager) strictly enforce execution limits (~25-30s) and kill non-compliant runtimes without warning (0x8badf00d SIGKILL). This standard prevents silent background eviction by enforcing deterministic chunking and graceful task termination. 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 Synchronization Causing Silent OS Watchdog SIGKILL and Battery Quota Depletion 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 Synchronization Causing Silent OS Watchdog SIGKILL and Battery Quota DepletionCritical
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 a hard execution budget cap of 20,000 milliseconds per background task to preserve an OS-required 5-10 second safety margin before native watchdog termination.

Engineers MUST ALWAYS enforce a hard execution budget cap of 20,000 milliseconds per background task to preserve an OS-required 5-10 second safety margin before native watchdog 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.
2

Engineers MUST NOT run unbounded arrays, continuous polling loops, or non-deterministic recursive promises within background runner callbacks.

Engineers MUST NOT run unbounded arrays, continuous polling loops, or non-deterministic recursive promises within background runner callbacks.

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 persist an atomic synchronization checkpoint (e.g., last processed cursor or sequence ID) after every individual atomic unit of work, allowing resumed execution in subsequent cycles.

Code SHOULD persist an atomic synchronization checkpoint (e.g., last processed cursor or sequence ID) after every individual atomic unit of work, allowing resumed execution in subsequent cycles.

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 invoke `BackgroundTask.finish({ taskId })` deterministically within a `finally` block or when reaching 80% of the elapsed time budget, whichever occurs first.

Services MUST invoke `BackgroundTask.finish({ taskId })` deterministically within a `finally` block or when reaching 80% of the elapsed time budget, whichever occurs first.

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 execute raw HTTP downloads, large binary mutations, or non-critical analytics in foreground-transition background events

Components NEVER execute raw HTTP downloads, large binary mutations, or non-critical analytics in foreground-transition background events; offload heavy jobs strictly to native WorkManager or BGProcessingTask bindings.

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 Task Execution OS Power-Budget Quarantine critical for AI coding assistants?

Enforces strict time-sliced execution budgets, thermal throttling, and atomic checkpointing for background jobs in Capacitor 7. Modern iOS (BGTaskScheduler) and Android (Doze/WorkManager) strictly enforce execution limits (~25-30s) and kill non-compliant runtimes without warning (0x8badf00d SIGKILL). This standard prevents silent background eviction by enforcing deterministic chunking and graceful task termination. 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 Synchronization Causing Silent OS Watchdog SIGKILL and Battery Quota Depletion) 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