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

Capacitor 7 Background Task Budgeting and WakeLock Enforcement

Enforces deterministic execution timeout fences and OS power governor compliance across iOS (BackgroundTasks/beginBackgroundTask) and Android (WorkManager/Doze Mode) in Capacitor 7. Mandates strict task budgeting fences (sub-25s on iOS), infallible completion handler dispatch via try/finally blocks, and idempotent Screen/CPU WakeLock acquisition-release cycles to prevent SIGKILL 0x8badf00d watchdog crashes and battery governor bans.

Prohibited Anti-Pattern: Unbounded Background Tasks and Leaked WakeLocks Triggering OS Watchdog Terminations

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 Background Task Budgeting and WakeLock Enforcement - Enforces deterministic execution timeout fences and OS power governor compliance across iOS (BackgroundTasks/beginBackgroundTask) and Android (WorkManager/Doze Mode) in Capacitor 7. Mandates strict task budgeting fences (sub-25s on iOS), infallible completion handler dispatch via try/finally blocks, and idempotent Screen/CPU WakeLock acquisition-release cycles to prevent SIGKILL 0x8badf00d watchdog crashes and battery governor bans.
globs: src/**/*.{ts,tsx}, ios/App/App/**/*.{swift,m}, android/app/src/main/**/*.{java,kt}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor-7-background-task-budgeting-wakelock-guardrails"
---

# Capacitor 7 Background Task Budgeting and WakeLock Enforcement

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Unbounded Background Tasks and Leaked WakeLocks Triggering OS Watchdog Terminations

## System Constraints
You are a Principal Mobile Architect enforcing Capacitor 7 Background Task Budgeting and WakeLock Guardrails. Mandate deterministic timeout fencing, guarantee the execution of finish() tokens on both native and bridge runtimes, and enforce strict state validation for WakeLock APIs under Android Doze mode and iOS Background Refresh policies.

## Strict Guidelines
- Engineers MUST ALWAYS wrap @capacitor/background-runner or @capacitor/background-task operations in an infallible try...finally block ensuring BackgroundTask.finish({ taskId }) executes unconditionally.
- Engineers MUST NEVER exceed a 25-second execution budget within iOS background task delegates; background operations must be bounded by an AbortController with a 20-second timeout fence to avoid the iOS 30-second watchdog SIGKILL (0x8badf00d).
- Services MUST release any acquired ScreenReader or KeepAwake WakeLock prior to entering background states, listening to App.addListener('appStateChange') events to prevent Android OS power governor blacklisting.
- Code MUST verify network and power constraints via native Network and Device APIs before scheduling heavy asynchronous synchronization queues in background tasks.
- Tasks running via native WorkManager delegates on Android MUST NOT execute continuous polling loops; defer to periodic WorkRequests or Push Notifications via FCM data payloads.
- Engineers MUST handle task cancellation callbacks natively (e.g., expirationHandler on iOS) to immediately abort pending network requests and flush telemetry buffers before process termination.

## Bad vs Good Implementations
### Background Task Budget Fence with Guaranteed Finish and AbortController

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: If the network request hangs, times out, or throws an unhandled rejection, BackgroundTask.finish is never called. iOS will terminate the app via the 0x8badf00d watchdog timer after 30 seconds, and future background execution permissions will be permanently throttled by iOS SpringBoard and Android Power Manager.
```typescript
import { BackgroundTask } from '@capacitor/background-task';
import { App } from '@capacitor/app';

App.addListener('appStateChange', async ({ isActive }) => {
  if (!isActive) {
    // ANTI-PATTERN: Leaks taskId if fetch fails or hangs. Exceeds OS execution budget,
    // leading to iOS watchdog SIGKILL 0x8badf00d and Android Doze kill.
    const taskId = await BackgroundTask.beforeExit(async () => {
      const response = await fetch('https://api.example.com/sync-heavy-state', {
        method: 'POST',
        body: JSON.stringify({ timestamp: Date.now() })
      });
      await response.json();
      BackgroundTask.finish({ taskId });
    });
  }
});
```

#### Production Standard (Correct)
> **Standard**: The good pattern enforces a strict 20-second AbortController timeout fence to cleanly preempt long-running requests before the OS kills the process. It wraps execution in a try...finally block to guarantee BackgroundTask.finish({ taskId }) runs unconditionally, and releases any active WakeLocks to adhere to power management policies.
```typescript
import { BackgroundTask } from '@capacitor/background-task';
import { App } from '@capacitor/app';
import { KeepAwake } from '@capacitor-community/keep-awake';

const BACKGROUND_TIMEOUT_MS = 20_000; // iOS hard fence is ~30s; bound at 20s

App.addListener('appStateChange', async ({ isActive }) => {
  if (isActive) {
    return;
  }

  // Invariant: Release any active wakelock immediately upon background transition
  await KeepAwake.isKeptAwake().then(async ({ isKeptAwake }) => {
    if (isKeptAwake) {
      await KeepAwake.allowSleep();
    }
  }).catch(() => {/* safe no-op */});

  let taskId: string | null = null;

  taskId = await BackgroundTask.beforeExit(async () => {
    const controller = new AbortController();
    const timeoutHandle = setTimeout(() => controller.abort(), BACKGROUND_TIMEOUT_MS);

    try {
      const response = await fetch('https://api.example.com/sync-heavy-state', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ timestamp: Date.now() }),
        signal: controller.signal
      });
      
      if (!response.ok) {
        throw new Error(`Sync failed with HTTP status ${response.status}`);
      }
      await response.json();
    } catch (err: unknown) {
      if ((err as Error)?.name === 'AbortError') {
        console.warn('[BackgroundSync] Execution aborted: Exceeded 20s budget');
      } else {
        console.error('[BackgroundSync] Execution error:', err);
      }
    } finally {
      clearTimeout(timeoutHandle);
      if (taskId !== null) {
        BackgroundTask.finish({ taskId });
      }
    }
  });
});
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Capacitor 7 Background Task Budgeting and WakeLock Enforcement

Capacitor 7 Background Task Budgeting and WakeLock Enforcement defines an industrial-grade behavioral standard for mobile engineering. Enforces deterministic execution timeout fences and OS power governor compliance across iOS (BackgroundTasks/beginBackgroundTask) and Android (WorkManager/Doze Mode) in Capacitor 7. Mandates strict task budgeting fences (sub-25s on iOS), infallible completion handler dispatch via try/finally blocks, and idempotent Screen/CPU WakeLock acquisition-release cycles to prevent SIGKILL 0x8badf00d watchdog crashes and battery governor bans. 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 Tasks and Leaked WakeLocks Triggering OS Watchdog Terminations 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 Tasks and Leaked WakeLocks Triggering OS Watchdog TerminationsCritical
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 wrap @capacitor/background-runner or @capacitor/background-task operations in an infallible try...finally block ensuring BackgroundTask.finish({ taskId }) executes unconditionally.

Engineers MUST ALWAYS wrap @capacitor/background-runner or @capacitor/background-task operations in an infallible try...finally block ensuring BackgroundTask.finish({ taskId }) executes unconditionally.

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 NEVER exceed a 25-second execution budget within iOS background task delegates

Engineers MUST NEVER exceed a 25-second execution budget within iOS background task delegates; background operations must be bounded by an AbortController with a 20-second timeout fence to avoid the iOS 30-second watchdog SIGKILL (0x8badf00d).

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

Services MUST release any acquired ScreenReader or KeepAwake WakeLock prior to entering background states, listening to App.addListener('appStateChange') events to prevent Android OS power governor blacklisting.

Services MUST release any acquired ScreenReader or KeepAwake WakeLock prior to entering background states, listening to App.addListener('appStateChange') events to prevent Android OS power governor blacklisting.

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 MUST verify network and power constraints via native Network and Device APIs before scheduling heavy asynchronous synchronization queues in background tasks.

Code MUST verify network and power constraints via native Network and Device APIs before scheduling heavy asynchronous synchronization queues in background tasks.

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

Tasks running via native WorkManager delegates on Android MUST NOT execute continuous polling loops

Tasks running via native WorkManager delegates on Android MUST NOT execute continuous polling loops; defer to periodic WorkRequests or Push Notifications via FCM data payloads.

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

Engineers MUST handle task cancellation callbacks natively (e.g., expirationHandler on iOS) to immediately abort pending network requests and flush telemetry buffers before process termination.

Engineers MUST handle task cancellation callbacks natively (e.g., expirationHandler on iOS) to immediately abort pending network requests and flush telemetry buffers before process 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.
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 Budgeting and WakeLock Enforcement critical for AI coding assistants?

Enforces deterministic execution timeout fences and OS power governor compliance across iOS (BackgroundTasks/beginBackgroundTask) and Android (WorkManager/Doze Mode) in Capacitor 7. Mandates strict task budgeting fences (sub-25s on iOS), infallible completion handler dispatch via try/finally blocks, and idempotent Screen/CPU WakeLock acquisition-release cycles to prevent SIGKILL 0x8badf00d watchdog crashes and battery governor bans. 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 Tasks and Leaked WakeLocks Triggering OS Watchdog Terminations) 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