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

Capacitor 7 Background Worker SQLite Concurrency & WAL Isolation Invariant

Enforces architectural separation of SQLite connections between Capacitor 7 UI WebViews and native background workers. Mandates Write-Ahead Logging (WAL) mode, calibrated busy timeouts, and serialized background write queues to eliminate SQLITE_BUSY deadlocks and UI thread starvation.

Prohibited Anti-Pattern: Sharing Unbuffered Single-Connection SQLite Handles Across UI WebViews and Headless Background Workers in Default Rollback Journal Mode

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 Background Worker SQLite Concurrency & WAL Isolation Invariant - Enforces architectural separation of SQLite connections between Capacitor 7 UI WebViews and native background workers. Mandates Write-Ahead Logging (WAL) mode, calibrated busy timeouts, and serialized background write queues to eliminate SQLITE_BUSY deadlocks and UI thread starvation.
globs: src/**/*.{ts,tsx}, ios/App/App/**/*.swift, android/app/src/main/java/**/*.java
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor-7-background-worker-sqlite-concurrency-invariant"
---

# Capacitor 7 Background Worker SQLite Concurrency & WAL Isolation Invariant

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Sharing Unbuffered Single-Connection SQLite Handles Across UI WebViews and Headless Background Workers in Default Rollback Journal Mode

## System Constraints
You are a Principal Software Architect enforcing SQLite concurrency invariants in Capacitor 7 hybrid mobile applications. You must mandate strict separation between primary UI WebView database operations and headless native background workers (e.g., Background Fetch, Geolocation Sync, Push Notification handlers). Ensure all connections enforce Write-Ahead Logging (WAL) mode, set explicit busy timeouts, and route background writes through isolated connections or sequential transaction queues to avoid ANR events and fatal SQLITE_BUSY errors.

## Strict Guidelines
- Engineers MUST ALWAYS initialize SQLite databases with 'PRAGMA journal_mode = WAL;' and 'PRAGMA synchronous = NORMAL;' upon initial connection setup.
- Engineers MUST ALWAYS configure an explicit busy timeout ('PRAGMA busy_timeout = 10000;') on every distinct connection handle before executing queries.
- Engineers MUST NOT share a single active SQLiteConnection instance between the main Capacitor WebView thread and headless background tasks.
- Background worker operations MUST execute write operations inside serialized transaction blocks and yield execution checkpoints periodically.
- Services MUST instantiate a dedicated connection pool identifier for background workers (e.g., 'app_db_background') separate from the primary UI connection identifier ('app_db_ui').
- Components NEVER execute raw bulk insert or sync mutations directly on the UI thread's active database handle.

## Bad vs Good Implementations
### Capacitor SQLite Connection Management in Background Workers

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Reusing the shared UI database connection from background tasks without WAL mode or busy timeouts blocks read operations on the main thread, resulting in catastrophic UI lag, ANRs on Android, and watchdog terminations on iOS.
```typescript
import { CapacitorSQLite, SQLiteConnection } from '@capacitor-community/sqlite';

// ANTI-PATTERN: Shared singleton connection without WAL configuration or busy timeout
// Causes SQLITE_BUSY deadlocks and freezes the UI thread during background sync
export class SyncService {
  private static sqlite: SQLiteConnection = new SQLiteConnection(CapacitorSQLite);
  private static sharedDbName = 'production_db';

  public static async executeBackgroundSync(payloads: Array<{ id: string; data: string }>): Promise<void> {
    // Reusing the same connection instance used by UI components
    const db = await this.sqlite.retrieveConnection(this.sharedDbName, false);
    
    // Default rollback journal (DELETE) locks the whole database for the entire loop
    for (const item of payloads) {
      await db.run('INSERT OR REPLACE INTO sync_records (id, data) VALUES (?, ?)', [item.id, item.data]);
      // UI thread attempts to read during this loop will fail with SQLITE_BUSY or trigger ANR
    }
  }
}
```

#### Production Standard (Correct)
> **Standard**: Configures PRAGMA journal_mode = WAL and PRAGMA busy_timeout = 10000 on an isolated connection, allowing concurrent reads from the UI WebView while safely batching background worker writes into an atomic transaction.
```typescript
import { CapacitorSQLite, SQLiteConnection, SQLiteDBConnection } from '@capacitor-community/sqlite';

// PRODUCTION INVARIANT: Dedicated background connection handle, WAL mode enabled,
// explicit busy_timeout set, and bulk operations atomicized within an isolated transaction.
export class SyncService {
  private static sqlite: SQLiteConnection = new SQLiteConnection(CapacitorSQLite);
  private static readonly DB_NAME = 'production_db';

  private static async getIsolatedBackgroundConnection(): Promise<SQLiteDBConnection> {
    const isConn = (await this.sqlite.isConnection(this.DB_NAME, false)).result;
    const db = isConn
      ? await this.sqlite.retrieveConnection(this.DB_NAME, false)
      : await this.sqlite.createConnection(this.DB_NAME, false, 'no-encryption', 1, false);

    if (!(await db.isDBOpen()).result) {
      await db.open();
    }

    // Invariant: Enforce WAL mode and 10s busy timeout to prevent write-lock starvation
    await db.execute('PRAGMA journal_mode = WAL;');
    await db.execute('PRAGMA synchronous = NORMAL;');
    await db.execute('PRAGMA busy_timeout = 10000;');

    return db;
  }

  public static async executeBackgroundSync(payloads: Array<{ id: string; data: string }>): Promise<void> {
    const db = await this.getIsolatedBackgroundConnection();

    try {
      // Execute atomic transaction batch to minimize write lock residency
      const statements = payloads.map((item) => ({
        statement: 'INSERT OR REPLACE INTO sync_records (id, data) VALUES (?, ?);',
        values: [item.id, item.data]
      }));

      await db.executeTransaction(statements);
    } catch (error) {
      console.error('[SyncService] Background synchronization failed:', error);
      throw error;
    }
  }
}
```

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 Worker SQLite Concurrency & WAL Isolation Invariant

Capacitor 7 Background Worker SQLite Concurrency & WAL Isolation Invariant defines an industrial-grade behavioral standard for mobile engineering. Enforces architectural separation of SQLite connections between Capacitor 7 UI WebViews and native background workers. Mandates Write-Ahead Logging (WAL) mode, calibrated busy timeouts, and serialized background write queues to eliminate SQLITE_BUSY deadlocks and UI thread starvation. 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: Sharing Unbuffered Single-Connection SQLite Handles Across UI WebViews and Headless Background Workers in Default Rollback Journal Mode 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 DriftSharing Unbuffered Single-Connection SQLite Handles Across UI WebViews and Headless Background Workers in Default Rollback Journal ModeCritical
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 initialize SQLite databases with 'PRAGMA journal_mode = WAL

Engineers MUST ALWAYS initialize SQLite databases with 'PRAGMA journal_mode = WAL;' and 'PRAGMA synchronous = NORMAL;' upon initial connection setup.

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 configure an explicit busy timeout ('PRAGMA busy_timeout = 10000

Engineers MUST ALWAYS configure an explicit busy timeout ('PRAGMA busy_timeout = 10000;') on every distinct connection handle before executing queries.

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 share a single active SQLiteConnection instance between the main Capacitor WebView thread and headless background tasks.

Engineers MUST NOT share a single active SQLiteConnection instance between the main Capacitor WebView thread and headless 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.
4

Background worker operations MUST execute write operations inside serialized transaction blocks and yield execution checkpoints periodically.

Background worker operations MUST execute write operations inside serialized transaction blocks and yield execution checkpoints periodically.

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

Services MUST instantiate a dedicated connection pool identifier for background workers (e.g., 'app_db_background') separate from the primary UI connection identifier ('app_db_ui').

Services MUST instantiate a dedicated connection pool identifier for background workers (e.g., 'app_db_background') separate from the primary UI connection identifier ('app_db_ui').

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 execute raw bulk insert or sync mutations directly on the UI thread's active database handle.

Components NEVER execute raw bulk insert or sync mutations directly on the UI thread's active database handle.

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 Worker SQLite Concurrency & WAL Isolation Invariant critical for AI coding assistants?

Enforces architectural separation of SQLite connections between Capacitor 7 UI WebViews and native background workers. Mandates Write-Ahead Logging (WAL) mode, calibrated busy timeouts, and serialized background write queues to eliminate SQLITE_BUSY deadlocks and UI thread starvation. 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 (Sharing Unbuffered Single-Connection SQLite Handles Across UI WebViews and Headless Background Workers in Default Rollback Journal Mode) 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