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

Capacitor 7 Headless Background Task Serialization and Lifecycle Standard

Enforces strict headless runtime teardown, sequential task serialization, and explicit bridge state flushing for Capacitor 7 background operations. Eliminates silent OS watchdog process termination (SIGKILL) on iOS and ANR timeouts on Android by bounding execution time to platform quotas and releasing WebView resource locks prior to suspension.

Prohibited Anti-Pattern: Unbounded Concurrent Background Promises with Leaked Native Bridge Listeners Causing OS Watchdog Termination

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 Headless Background Task Serialization and Lifecycle Standard - Enforces strict headless runtime teardown, sequential task serialization, and explicit bridge state flushing for Capacitor 7 background operations. Eliminates silent OS watchdog process termination (SIGKILL) on iOS and ANR timeouts on Android by bounding execution time to platform quotas and releasing WebView resource locks prior to suspension.
globs: src/**/background/**/*.{ts,tsx}, src/**/services/**/*.{ts,tsx}, src/**/workers/**/*.{ts,tsx}, src/**/sync/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor-7-background-task-serialization-standard"
---

# Capacitor 7 Headless Background Task Serialization and Lifecycle Standard

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Unbounded Concurrent Background Promises with Leaked Native Bridge Listeners Causing OS Watchdog Termination

## System Constraints
You are a Principal Mobile Architect enforcing Capacitor 7 Background Task Serialization and Lifecycle standards. In iOS and Android hybrid architectures, background tasks execute under aggressive OS-enforced CPU, memory, and time constraints (e.g., iOS 30-second assertion limit, Android WorkManager/JobScheduler constraints). You must guarantee that every background sync or task strictly adheres to: (1) deterministic async mutex serialization to prevent concurrent execution races, (2) explicit try/finally termination of native background IDs via BackgroundTask.finish(), (3) strict teardown of bridge listeners and active DOM/network references before suspension, and (4) atomic serialized persistence of sync state to disk before signaling task completion.

## Strict Guidelines
- Engineers MUST ALWAYS wrap native background operations within App.addListener('appStateChange') or BackgroundTask.beforeExit in a deterministic try/finally block that unconditionally calls BackgroundTask.finish({ taskId }).
- Engineers MUST NOT initiate concurrent or unbatched parallel native bridge calls inside background execution loops; operations must be serialized using an explicit task queue or mutex.
- Services MUST serialize sync state atomically to durable storage (e.g., SQLite or Preferences) and complete all disk I/O flushes before invoking native task completion.
- Engineers MUST teardown event listeners, abort ongoing AbortController instances, and clear timers when transition to background reaches the watchdog deadline (targeting < 25s on iOS).
- Components NEVER trigger UI re-renders or retain reactive DOM bindings during headless background execution cycles.

## Bad vs Good Implementations
### Headless Background Synchronization and Resource Teardown

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Launching unbounded async operations with forEach leaves unhandled microtasks executing after BackgroundTask.finish() is called prematurely. If the network stalls, the OS watchdog terminates the process with SIGKILL (0x8badf00d on iOS) due to exceeding background runtime limits without clean bridge teardown.
```typescript
import { App } from '@capacitor/app';
import { BackgroundTask } from '@capawesome/capacitor-background-task';

// Anti-pattern: Missing deterministic timeout, no state serialization lock,
// dangling promises, and failure to guarantee finish() on error or timeout.
App.addListener('appStateChange', async ({ isActive }) => {
  if (!isActive) {
    const taskId = await BackgroundTask.beforeExit(async () => {
      // Unbounded concurrent requests leak native bridge memory
      const pendingRecords = await fetchPendingRecords();
      pendingRecords.forEach(async (record) => {
        await uploadRecord(record);
      });
      // finish() called before async operations actually complete
      BackgroundTask.finish({ taskId });
    });
  }
});
```

#### Production Standard (Correct)
> **Standard**: Implements an async mutex lock to block concurrent sync cycles, bounds execution strictly beneath the iOS watchdog threshold with an AbortController, serializes requests to preserve bridge memory, atomically flushes state to disk, and guarantees BackgroundTask.finish() is executed in a defensive finally block.
```typescript
import { App, type PluginListenerHandle } from '@capacitor/app';
import { BackgroundTask } from '@capawesome/capacitor-background-task';
import { Preferences } from '@capacitor/preferences';

interface SyncState {
  lastSyncTimestamp: number;
  pendingCount: number;
}

class SerializedSyncService {
  private static isSyncing = false;
  private static readonly MAX_BACKGROUND_TIME_MS = 25_000; // Safe threshold below iOS 30s limit

  public static async executeBackgroundCycle(): Promise<void> {
    if (this.isSyncing) return;
    this.isSyncing = true;

    let taskId: string | null = null;
    const abortController = new AbortController();
    const timeoutId = setTimeout(() => abortController.abort(), this.MAX_BACKGROUND_TIME_MS);

    try {
      taskId = await BackgroundTask.beforeExit(async () => {
        try {
          const queue = await this.loadPendingQueue();
          // Strict sequential serialization to avoid native bridge memory spikes
          for (const item of queue) {
            if (abortController.signal.aborted) break;
            await this.processItem(item, abortController.signal);
          }
          await this.flushStateToDisk({ lastSyncTimestamp: Date.now(), pendingCount: 0 });
        } finally {
          if (taskId) {
            await BackgroundTask.finish({ taskId });
            taskId = null;
          }
        }
      });
    } catch (err: unknown) {
      console.error('Fatal background sync error', err);
    } finally {
      clearTimeout(timeoutId);
      this.isSyncing = false;
      if (taskId) {
        await BackgroundTask.finish({ taskId });
      }
    }
  }

  private static async loadPendingQueue(): Promise<string[]> {
    const { value } = await Preferences.get({ key: 'sync_queue' });
    return value ? JSON.parse(value) : [];
  }

  private static async processItem(item: string, signal: AbortSignal): Promise<void> {
    await fetch('/api/sync', { method: 'POST', body: JSON.stringify({ item }), signal });
  }

  private static async flushStateToDisk(state: SyncState): Promise<void> {
    await Preferences.set({ key: 'sync_state', value: JSON.stringify(state) });
  }
}

let listenerHandle: PluginListenerHandle | null = null;

export const initializeBackgroundLifecycle = async (): Promise<void> => {
  if (listenerHandle) await listenerHandle.remove();
  listenerHandle = await App.addListener('appStateChange', async ({ isActive }) => {
    if (!isActive) {
      await SerializedSyncService.executeBackgroundCycle();
    }
  });
};
```

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 Headless Background Task Serialization and Lifecycle Standard

Capacitor 7 Headless Background Task Serialization and Lifecycle Standard defines an industrial-grade behavioral standard for mobile engineering. Enforces strict headless runtime teardown, sequential task serialization, and explicit bridge state flushing for Capacitor 7 background operations. Eliminates silent OS watchdog process termination (SIGKILL) on iOS and ANR timeouts on Android by bounding execution time to platform quotas and releasing WebView resource locks prior to suspension. 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 Concurrent Background Promises with Leaked Native Bridge Listeners Causing OS Watchdog Termination 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 Concurrent Background Promises with Leaked Native Bridge Listeners Causing OS Watchdog TerminationCritical
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 native background operations within App.addListener('appStateChange') or BackgroundTask.beforeExit in a deterministic try/finally block that unconditionally calls BackgroundTask.finish({ taskId }).

Engineers MUST ALWAYS wrap native background operations within App.addListener('appStateChange') or BackgroundTask.beforeExit in a deterministic try/finally block that unconditionally calls BackgroundTask.finish({ taskId }).

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 initiate concurrent or unbatched parallel native bridge calls inside background execution loops

Engineers MUST NOT initiate concurrent or unbatched parallel native bridge calls inside background execution loops; operations must be serialized using an explicit task queue or mutex.

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 serialize sync state atomically to durable storage (e.g., SQLite or Preferences) and complete all disk I/O flushes before invoking native task completion.

Services MUST serialize sync state atomically to durable storage (e.g., SQLite or Preferences) and complete all disk I/O flushes before invoking native task completion.

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

Engineers MUST teardown event listeners, abort ongoing AbortController instances, and clear timers when transition to background reaches the watchdog deadline (targeting < 25s on iOS).

Engineers MUST teardown event listeners, abort ongoing AbortController instances, and clear timers when transition to background reaches the watchdog deadline (targeting < 25s on iOS).

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 UI re-renders or retain reactive DOM bindings during headless background execution cycles.

Components NEVER trigger UI re-renders or retain reactive DOM bindings during headless background execution 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.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:Why is Capacitor 7 Headless Background Task Serialization and Lifecycle Standard critical for AI coding assistants?

Enforces strict headless runtime teardown, sequential task serialization, and explicit bridge state flushing for Capacitor 7 background operations. Eliminates silent OS watchdog process termination (SIGKILL) on iOS and ANR timeouts on Android by bounding execution time to platform quotas and releasing WebView resource locks prior to suspension. 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 Concurrent Background Promises with Leaked Native Bridge Listeners Causing OS Watchdog Termination) 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