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

Capacitor 7 Background Task Suspension Boundaries and Watchdog Resiliency

Mandates deterministic background execution lifecycles and atomic persistence boundaries during Capacitor 7 app suspension. Prevents OS watchdog terminations (e.g., iOS 0x8badf00d, Android ANR) and half-written state by bounding background operations within strict hardware timeouts and guaranteed task completion tokens.

Prohibited Anti-Pattern: Unbounded Async Operations and Non-Atomic Persistence in App Suspension Callbacks

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 Background Task Suspension Boundaries and Watchdog Resiliency - Mandates deterministic background execution lifecycles and atomic persistence boundaries during Capacitor 7 app suspension. Prevents OS watchdog terminations (e.g., iOS 0x8badf00d, Android ANR) and half-written state by bounding background operations within strict hardware timeouts and guaranteed task completion tokens.
globs: src/**/*.{ts,tsx}, src/services/**/*.{ts,tsx}, src/lifecycle/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor-7-background-task-watchdog-resiliency"
---

# Capacitor 7 Background Task Suspension Boundaries and Watchdog Resiliency

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Unbounded Async Operations and Non-Atomic Persistence in App Suspension Callbacks

## System Constraints
You are a Principal Mobile Architect enforcing Capacitor 7 Background Task Lifecycle & OS Watchdog Resiliency. Mandate strict execution bounds on all lifecycle transitions. Reject any asynchronous operations during `appStateChange` that do not acquire native background task tokens, fail to enforce hard timeouts before OS watchdog limits, or leave state persistence open to mid-flight corruption.

## Strict Guidelines
- Engineers MUST ALWAYS wrap background execution in native task tokens (e.g., `BackgroundTask.beforeExit`) to inform the OS execution scheduler before starting async persistence.
- Engineers MUST ALWAYS implement an `AbortController` bounded by an internal watchdog timeout set at least 3,000ms below the OS ceiling (max 25s on iOS, 5s on immediate suspension paths).
- Engineers MUST ALWAYS guarantee execution of task completion handlers (e.g., `BackgroundTask.finish({ taskId })`) in a `finally` block, ensuring tokens are released under error or abort conditions.
- Services MUST serialize background state commits into atomic filesystem swap operations (write-to-temporary-file followed by atomic rename) instead of sequential key-value writes.
- Engineers MUST NOT execute blocking network calls or non-idempotent remote synchronization routines inside suspension-time background hooks without persistent queue recovery.

## Bad vs Good Implementations
### Suspension Lifecycle Task with Watchdog Guard and Atomic Flush

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The handler registers an untracked async promise during app suspension. Operating systems (especially iOS) will not grant execution time without an active background task token, leading to immediate thread freezing or watchdog termination (0x8badf00d). If frozen mid-write, multi-key preferences desynchronize, causing critical state corruption on subsequent launches.
```typescript
import { App } from '@capacitor/app';
import { Preferences } from '@capacitor/preferences';

// ANTI-PATTERN: Naked async callback without native background execution tokens,
// indefinite timeout, and non-atomic multiple storage writes.
App.addListener('appStateChange', async (state) => {
  if (!state.isActive) {
    // The OS scheduler may terminate or freeze the process mid-execution,
    // causing iOS 0x8badf00d watchdog kills or corrupted application state.
    await fetch('https://api.example.com/sync', {
      method: 'POST',
      body: JSON.stringify({ event: 'backgrounded' }),
    });
    
    await Preferences.set({ key: 'user_session', value: JSON.stringify({ active: false }) });
    await Preferences.set({ key: 'dirty_flag', value: 'false' });
  }
});
```

#### Production Standard (Correct)
> **Standard**: Acquires a native background execution token using BackgroundTask.beforeExit to ensure OS thread scheduling. Guards the execution block with an AbortController watchdog capped at 20 seconds to prevent watchdog kills. Persists state using an atomic write-and-rename pattern to ensure zero corruption, and guarantees BackgroundTask.finish({ taskId }) is called in the finally block.
```typescript
import { App, AppState } from '@capacitor/app';
import { Filesystem, Directory, Encoding } from '@capacitor/filesystem';
import { BackgroundTask } from '@capawesome/capacitor-background-task';

const WATCHDOG_TIMEOUT_MS = 20_000; // iOS allows ~30s; bound at 20s for safe margin

interface SessionState {
  isActive: boolean;
  timestamp: number;
}

async function atomicStateCommit(state: SessionState): Promise<void> {
  const tempFile = `session_commit_${Date.now()}.tmp`;
  const targetFile = 'session_state.json';
  
  await Filesystem.writeFile({
    path: tempFile,
    data: JSON.stringify(state),
    directory: Directory.Data,
    encoding: Encoding.UTF8,
  });

  await Filesystem.rename({
    from: tempFile,
    to: targetFile,
    directory: Directory.Data,
  });
}

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

  const taskId = await BackgroundTask.beforeExit(async () => {
    const abortController = new AbortController();
    const timeoutId = setTimeout(() => abortController.abort(), WATCHDOG_TIMEOUT_MS);

    try {
      const commitPromise = atomicStateCommit({
        isActive: false,
        timestamp: Date.now(),
      });

      const watchdogRace = new Promise<never>((_, reject) => {
        abortController.signal.addEventListener('abort', () => {
          reject(new Error('Watchdog timeout reached: Aborting background commit'));
        });
      });

      await Promise.race([commitPromise, watchdogRace]);
    } catch (error) {
      console.error('Suspension handler interrupted or failed:', error);
    } finally {
      clearTimeout(timeoutId);
      BackgroundTask.finish({ taskId });
    }
  });
});
```

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 Task Suspension Boundaries and Watchdog Resiliency

Capacitor 7 Background Task Suspension Boundaries and Watchdog Resiliency defines an industrial-grade behavioral standard for mobile engineering. Mandates deterministic background execution lifecycles and atomic persistence boundaries during Capacitor 7 app suspension. Prevents OS watchdog terminations (e.g., iOS 0x8badf00d, Android ANR) and half-written state by bounding background operations within strict hardware timeouts and guaranteed task completion tokens. 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 Async Operations and Non-Atomic Persistence in App Suspension Callbacks 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 Async Operations and Non-Atomic Persistence in App Suspension CallbacksCritical
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 background execution in native task tokens (e.g., `BackgroundTask.beforeExit`) to inform the OS execution scheduler before starting async persistence.

Engineers MUST ALWAYS wrap background execution in native task tokens (e.g., `BackgroundTask.beforeExit`) to inform the OS execution scheduler before starting async persistence.

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 implement an `AbortController` bounded by an internal watchdog timeout set at least 3,000ms below the OS ceiling (max 25s on iOS, 5s on immediate suspension paths).

Engineers MUST ALWAYS implement an `AbortController` bounded by an internal watchdog timeout set at least 3,000ms below the OS ceiling (max 25s on iOS, 5s on immediate suspension paths).

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 ALWAYS guarantee execution of task completion handlers (e.g., `BackgroundTask.finish({ taskId })`) in a `finally` block, ensuring tokens are released under error or abort conditions.

Engineers MUST ALWAYS guarantee execution of task completion handlers (e.g., `BackgroundTask.finish({ taskId })`) in a `finally` block, ensuring tokens are released under error or abort conditions.

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 serialize background state commits into atomic filesystem swap operations (write-to-temporary-file followed by atomic rename) instead of sequential key-value writes.

Services MUST serialize background state commits into atomic filesystem swap operations (write-to-temporary-file followed by atomic rename) instead of sequential key-value writes.

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

Engineers MUST NOT execute blocking network calls or non-idempotent remote synchronization routines inside suspension-time background hooks without persistent queue recovery.

Engineers MUST NOT execute blocking network calls or non-idempotent remote synchronization routines inside suspension-time background hooks without persistent queue recovery.

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 Suspension Boundaries and Watchdog Resiliency critical for AI coding assistants?

Mandates deterministic background execution lifecycles and atomic persistence boundaries during Capacitor 7 app suspension. Prevents OS watchdog terminations (e.g., iOS 0x8badf00d, Android ANR) and half-written state by bounding background operations within strict hardware timeouts and guaranteed task completion tokens. 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 Async Operations and Non-Atomic Persistence in App Suspension Callbacks) 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