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

Capacitor 7 Background Task State Serialization & Atomic Flush Guardrail

Enforces deterministic, atomic local state persistence within OS-allotted execution budgets when Capacitor 7 mobile applications transition to the background. Eliminates silent data loss, memory-state evictions, and SQLite lock corruption caused by uncoordinated JavaScript execution during iOS watchdog terminations and Android low-memory killer (LMK) process purges.

Prohibited Anti-Pattern: Fire-and-Forget Async State Persistence During Backgrounding Without Native OS Task Registration

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 Background Task State Serialization & Atomic Flush Guardrail - Enforces deterministic, atomic local state persistence within OS-allotted execution budgets when Capacitor 7 mobile applications transition to the background. Eliminates silent data loss, memory-state evictions, and SQLite lock corruption caused by uncoordinated JavaScript execution during iOS watchdog terminations and Android low-memory killer (LMK) process purges.
globs: src/**/*.{ts,tsx}, src/services/**/*.{ts,tsx}, src/store/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor-7-background-task-state-serialization-guardrail"
---

# Capacitor 7 Background Task State Serialization & Atomic Flush Guardrail

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Fire-and-Forget Async State Persistence During Backgrounding Without Native OS Task Registration

## System Constraints
You are a Principal Mobile Architect specializing in hybrid runtimes and Capacitor 7 systems. You mandate strict architectural guardrails around app lifecycle transitions and background execution. Operating systems (iOS via Watchdog and Android via Low Memory Killer/Doze) terminate suspended WebViews without invoking asynchronous garbage collectors or awaiting microtasks. You must strictly enforce atomic persistence, bounded flush timeouts, and explicit native background task lease acquisitions before relinquishing execution.

## Strict Guidelines
- Engineers MUST ALWAYS register an explicit native background task lease via `BackgroundTask.beforeExit()` immediately upon detecting an `appStateChange` event where `isActive` becomes `false`.
- Engineers MUST wrap all background persistence routines in an atomic timeout race (maximum 15,000ms for iOS compliance) to ensure the native lease is safely surrendered via `BackgroundTask.finish({ taskId })` before the OS terminates the process.
- Engineers MUST NOT rely on browser-level `localStorage`, `sessionStorage`, or uncoordinated IndexedDB writes during backgrounding, as WebKit suspends and occasionally purges uncommitted leveldb journals during process freeze.
- Persistence pipelines MUST use transactional storage (e.g., Capacitor SQLite with Write-Ahead Logging or atomic file writes via atomic rename patterns) to prevent corrupting state caches on sudden kill.
- State synchronization handlers MUST execute as an isolated, idempotent atomic pipeline, separating local staging from remote HTTP network sync; remote sync MUST yield immediately if the background grace period drops below safety margins (3 seconds remaining).
- Components NEVER attach disconnected asynchronous lifecycle listeners; background persistence handlers MUST be centrally orchestrated in a dedicated LifecycleCoordinator service.

## Bad vs Good Implementations
### Unbounded Async Background Handler Causing Process Termination (Anti-Pattern)

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The handler initiates unmanaged async promises when the app is backgrounded. Mobile OSs (especially iOS) freeze the WebKit JavaScript thread within milliseconds unless a background task assertion is acquired. This leads to partial I/O operations, deadlocked indexedDB handles, and silent failure of the network sync without notifying the user or recovering state.
```typescript
import { App } from '@capacitor/app';
import { useAppStore } from './store';

// ANTI-PATTERN: Relying on plain JS event loop and unmanaged async calls
App.addListener('appStateChange', async (state) => {
  if (!state.isActive) {
    const store = useAppStore.getState();
    
    // Race condition: iOS will freeze the JS runtime mid-execution,
    // corrupting writes or failing network sync silently.
    await store.persistDirtyEntities();
    await fetch('https://api.example.com/sync', {
      method: 'POST',
      body: JSON.stringify(store.dirtyEntities),
    });
    console.log('Sync complete');
  }
});
```

#### Production Standard (Correct)
> **Standard**: Acquires an explicit native background task token via `BackgroundTask.beforeExit`, wraps atomic transactional persistence inside SQLite, bounds execution with a 14-second watchdog timer, guarantees that `finish({ taskId })` runs in a `finally` block, and ignores slow network operations to prioritize zero-loss disk serialization.
```typescript
import { App, AppState } from '@capacitor/app';
import { BackgroundTask } from '@capawesome/capacitor-background-task';
import { localDb } from './database/sqlite';
import { stateRegistry } from './store/registry';

const BACKGROUND_WATCHDOG_LIMIT_MS = 14000; // Strict boundary below iOS ~25-30s limit

export class BackgroundPersistenceCoordinator {
  private static isSerializing = false;

  public static initialize(): void {
    App.addListener('appStateChange', async (state: AppState) => {
      if (!state.isActive) {
        await this.handleBackgroundTransition();
      }
    });
  }

  private static async handleBackgroundTransition(): Promise<void> {
    if (this.isSerializing) return;
    this.isSerializing = true;

    let taskId: string | null = null;

    try {
      taskId = await BackgroundTask.beforeExit(async () => {
        // Native OS warning that time has expired; immediately resolve to prevent sigkill
        if (taskId) {
          BackgroundTask.finish({ taskId });
          taskId = null;
        }
      });

      const persistenceOperation = async () => {
        const dirtyPayload = stateRegistry.extractDirtySnapshot();
        if (!dirtyPayload) return;

        // Atomic write via transaction using Capacitor SQLite
        await localDb.executeTransaction(async (tx) => {
          await tx.execute(
            'INSERT INTO state_snapshots (id, payload, timestamp) VALUES (?, ?, ?)',
            [dirtyPayload.id, JSON.stringify(dirtyPayload.data), Date.now()]
          );
          await tx.execute('UPDATE sync_queue SET status = "STAGED" WHERE status = "PENDING"');
        });

        stateRegistry.markFlushed(dirtyPayload.id);
      };

      const watchdogTimeout = new Promise<never>((_, reject) =>
        setTimeout(() => reject(new Error('Background flush exceeded safety threshold')), BACKGROUND_WATCHDOG_LIMIT_MS)
      );

      await Promise.race([persistenceOperation(), watchdogTimeout]);
    } catch (error) {
      console.error('[BackgroundPersistenceCoordinator] Critical serialization failure:', error);
    } finally {
      this.isSerializing = false;
      if (taskId) {
        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 State Serialization & Atomic Flush Guardrail

Capacitor 7 Background Task State Serialization & Atomic Flush Guardrail defines an industrial-grade behavioral standard for mobile engineering. Enforces deterministic, atomic local state persistence within OS-allotted execution budgets when Capacitor 7 mobile applications transition to the background. Eliminates silent data loss, memory-state evictions, and SQLite lock corruption caused by uncoordinated JavaScript execution during iOS watchdog terminations and Android low-memory killer (LMK) process purges. 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: Fire-and-Forget Async State Persistence During Backgrounding Without Native OS Task Registration 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 DriftFire-and-Forget Async State Persistence During Backgrounding Without Native OS Task RegistrationCritical
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 register an explicit native background task lease via `BackgroundTask.beforeExit()` immediately upon detecting an `appStateChange` event where `isActive` becomes `false`.

Engineers MUST ALWAYS register an explicit native background task lease via `BackgroundTask.beforeExit()` immediately upon detecting an `appStateChange` event where `isActive` becomes `false`.

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 wrap all background persistence routines in an atomic timeout race (maximum 15,000ms for iOS compliance) to ensure the native lease is safely surrendered via `BackgroundTask.finish({ taskId })` before the OS terminates the process.

Engineers MUST wrap all background persistence routines in an atomic timeout race (maximum 15,000ms for iOS compliance) to ensure the native lease is safely surrendered via `BackgroundTask.finish({ taskId })` before the OS terminates the process.

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 rely on browser-level `localStorage`, `sessionStorage`, or uncoordinated IndexedDB writes during backgrounding, as WebKit suspends and occasionally purges uncommitted leveldb journals during process freeze.

Engineers MUST NOT rely on browser-level `localStorage`, `sessionStorage`, or uncoordinated IndexedDB writes during backgrounding, as WebKit suspends and occasionally purges uncommitted leveldb journals during process freeze.

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

Persistence pipelines MUST use transactional storage (e.g., Capacitor SQLite with Write-Ahead Logging or atomic file writes via atomic rename patterns) to prevent corrupting state caches on sudden kill.

Persistence pipelines MUST use transactional storage (e.g., Capacitor SQLite with Write-Ahead Logging or atomic file writes via atomic rename patterns) to prevent corrupting state caches on sudden kill.

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

State synchronization handlers MUST execute as an isolated, idempotent atomic pipeline, separating local staging from remote HTTP network sync

State synchronization handlers MUST execute as an isolated, idempotent atomic pipeline, separating local staging from remote HTTP network sync; remote sync MUST yield immediately if the background grace period drops below safety margins (3 seconds remaining).

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 attach disconnected asynchronous lifecycle listeners

Components NEVER attach disconnected asynchronous lifecycle listeners; background persistence handlers MUST be centrally orchestrated in a dedicated LifecycleCoordinator service.

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 State Serialization & Atomic Flush Guardrail critical for AI coding assistants?

Enforces deterministic, atomic local state persistence within OS-allotted execution budgets when Capacitor 7 mobile applications transition to the background. Eliminates silent data loss, memory-state evictions, and SQLite lock corruption caused by uncoordinated JavaScript execution during iOS watchdog terminations and Android low-memory killer (LMK) process purges. 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 (Fire-and-Forget Async State Persistence During Backgrounding Without Native OS Task Registration) 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