This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: capacitor-7-native-bridge-thread-pool-quarantine

Capacitor 7 Native Bridge Thread-Pool Concurrency Quarantine

Heavy filesystem I/O, cryptographic computations, and biometric authorizations executed across the Capacitor 7 bridge must be explicitly quarantined from the native UI dispatch queue and throttled against the WebView event loop. Failure to segregate asynchronous native thread pools from main-thread bridge callbacks introduces severe UI micro-stutters, IPC message queue starvation, and dropped 60/120Hz display frames.

Prohibited Anti-Pattern: Executing heavy native file I/O or cryptographic routines on the main UI dispatch queue via unthrottled bridge calls.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 Native Bridge Thread-Pool Concurrency Quarantine - Heavy filesystem I/O, cryptographic computations, and biometric authorizations executed across the Capacitor 7 bridge must be explicitly quarantined from the native UI dispatch queue and throttled against the WebView event loop. Failure to segregate asynchronous native thread pools from main-thread bridge callbacks introduces severe UI micro-stutters, IPC message queue starvation, and dropped 60/120Hz display frames.
globs: src/**/*.{ts,tsx}, ios/App/App/**/*.swift, android/app/src/main/**/*.kt
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor-7-native-bridge-thread-pool-quarantine"
---

# Capacitor 7 Native Bridge Thread-Pool Concurrency Quarantine

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Executing heavy native file I/O or cryptographic routines on the main UI dispatch queue via unthrottled bridge calls.

## System Constraints
You are a Principal Mobile Architect enforcing Capacitor 7 Native Bridge Thread-Pool Concurrency Quarantine. You must prevent hybrid WebView frame drops and thread starvation by ensuring native plugins offload expensive operations to dedicated background worker queues (DispatchQueue.global / Dispatchers.IO) and client-side TypeScript callers throttle high-volume bridge invocations away from UI render ticks.

## Strict Guidelines
- Engineers MUST ALWAYS route heavy native filesystem, cryptographic, and biometric operations to dedicated background executors (DispatchQueue.global(qos: .userInitiated) on iOS or Dispatchers.IO on Android) before notifying the Capacitor bridge.
- Engineers MUST NOT invoke native bridge plugins synchronously within 60fps/120fps UI render paths, touch-drag handlers, or requestAnimationFrame cycles.
- Code SHOULD implement client-side bridge concurrency limiters (e.g., task queues with max concurrency ≤ 2) when processing batched native operations to prevent IPC serialization saturation.
- Services MUST yield control back to the WebView microtask queue (via scheduler.yield() or setTimeout(..., 0)) before initiating subsequent native plugin bridge transactions.
- Components NEVER execute raw bulk data transformations directly in the main WebView thread prior to passing them through the native bridge; offload bulk serialization to dedicated Web Workers.

## Bad vs Good Implementations
### Batch Native Bridge File Processing with Concurrency Quarantine

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Launching unbounded concurrent Filesystem calls hammers the Capacitor message pump, exhausting native bridge worker queues and causing jank in WebView CSS animations and touch response.
```typescript
import { Filesystem, Directory } from '@capacitor/filesystem';

// ANTI-PATTERN: Unbounded concurrent bridge calls saturate the IPC channel
// and starve the WebView main thread during active UI animations.
export async function processAllImages(filePaths: string[]): Promise<string[]> {
  return Promise.all(
    filePaths.map(async (path) => {
      const result = await Filesystem.readFile({
        path,
        directory: Directory.Data
      });
      return result.data as string;
    })
  );
}
```

#### Production Standard (Correct)
> **Standard**: Constrains concurrent bridge invocations to a safe maximum (2 workers) and introduces explicit scheduler yields between read calls, ensuring the hybrid WebView event loop and display refresh cycles remain uninterrupted.
```typescript
import { Filesystem, Directory } from '@capacitor/filesystem';

interface QueueOptions {
  concurrency?: number;
}

// PRODUCTION FIX: Strict bridge concurrency quarantine and microtask yielding
export async function processAllImages(
  filePaths: string[],
  options: QueueOptions = {}
): Promise<string[]> {
  const maxConcurrency = options.concurrency ?? 2;
  const results: string[] = new Array(filePaths.length);
  let currentIndex = 0;

  async function worker(): Promise<void> {
    while (currentIndex < filePaths.length) {
      const index = currentIndex++;
      const path = filePaths[index];

      // Yield to allow the browser engine to paint pending frame updates
      if ('yield' in window.scheduler) {
        await (window.scheduler as { yield: () => Promise<void> }).yield();
      } else {
        await new Promise((resolve) => setTimeout(resolve, 0));
      }

      const response = await Filesystem.readFile({
        path,
        directory: Directory.Data
      });

      results[index] = response.data as string;
    }
  }

  const workers = Array.from(
    { length: Math.min(maxConcurrency, filePaths.length) },
    () => worker()
  );

  await Promise.all(workers);
  return results;
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Capacitor 7 Native Bridge Thread-Pool Concurrency Quarantine

Capacitor 7 Native Bridge Thread-Pool Concurrency Quarantine defines an industrial-grade behavioral standard for mobile engineering. Heavy filesystem I/O, cryptographic computations, and biometric authorizations executed across the Capacitor 7 bridge must be explicitly quarantined from the native UI dispatch queue and throttled against the WebView event loop. Failure to segregate asynchronous native thread pools from main-thread bridge callbacks introduces severe UI micro-stutters, IPC message queue starvation, and dropped 60/120Hz display frames. 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: Executing heavy native file I/O or cryptographic routines on the main UI dispatch queue via unthrottled bridge calls. 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 DriftExecuting heavy native file I/O or cryptographic routines on the main UI dispatch queue via unthrottled bridge calls.Critical
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 route heavy native filesystem, cryptographic, and biometric operations to dedicated background executors (DispatchQueue.global(qos

Engineers MUST ALWAYS route heavy native filesystem, cryptographic, and biometric operations to dedicated background executors (DispatchQueue.global(qos: .userInitiated) on iOS or Dispatchers.IO on Android) before notifying the Capacitor bridge.

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 invoke native bridge plugins synchronously within 60fps/120fps UI render paths, touch-drag handlers, or requestAnimationFrame cycles.

Engineers MUST NOT invoke native bridge plugins synchronously within 60fps/120fps UI render paths, touch-drag handlers, or requestAnimationFrame 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.
3

Code SHOULD implement client-side bridge concurrency limiters (e.g., task queues with max concurrency ≤ 2) when processing batched native operations to prevent IPC serialization saturation.

Code SHOULD implement client-side bridge concurrency limiters (e.g., task queues with max concurrency ≤ 2) when processing batched native operations to prevent IPC serialization saturation.

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 yield control back to the WebView microtask queue (via scheduler.yield() or setTimeout(..., 0)) before initiating subsequent native plugin bridge transactions.

Services MUST yield control back to the WebView microtask queue (via scheduler.yield() or setTimeout(..., 0)) before initiating subsequent native plugin bridge transactions.

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 execute raw bulk data transformations directly in the main WebView thread prior to passing them through the native bridge

Components NEVER execute raw bulk data transformations directly in the main WebView thread prior to passing them through the native bridge; offload bulk serialization to dedicated Web Workers.

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 Native Bridge Thread-Pool Concurrency Quarantine critical for AI coding assistants?

Heavy filesystem I/O, cryptographic computations, and biometric authorizations executed across the Capacitor 7 bridge must be explicitly quarantined from the native UI dispatch queue and throttled against the WebView event loop. Failure to segregate asynchronous native thread pools from main-thread bridge callbacks introduces severe UI micro-stutters, IPC message queue starvation, and dropped 60/120Hz display frames. 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 (Executing heavy native file I/O or cryptographic routines on the main UI dispatch queue via unthrottled bridge calls.) 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