This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: react-native-jsi-direct-buffer-exchange

Zero-Copy JSI ArrayBuffer Streaming for High-Frequency Native Buffers

Mandates the usage of direct C++ JSI ArrayBuffer encapsulation and shared-memory HostObjects for streaming high-frequency biometric, audio, and visual data to the JavaScript engine. Prohibits Base64 conversion, JSON serialization, and per-frame heap allocations over the React Native bridge or TurboModule message queues.

Prohibited Anti-Pattern: Serializing High-Frequency Binary Streams into Base64 or JSON Over Async TurboModule Promises

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Zero-Copy JSI ArrayBuffer Streaming for High-Frequency Native Buffers - Mandates the usage of direct C++ JSI ArrayBuffer encapsulation and shared-memory HostObjects for streaming high-frequency biometric, audio, and visual data to the JavaScript engine. Prohibits Base64 conversion, JSON serialization, and per-frame heap allocations over the React Native bridge or TurboModule message queues.
globs: src/**/*.{ts,tsx}, cpp/**/*.{h,cpp}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/react-native-jsi-direct-buffer-exchange"
---

# Zero-Copy JSI ArrayBuffer Streaming for High-Frequency Native Buffers

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Serializing High-Frequency Binary Streams into Base64 or JSON Over Async TurboModule Promises

## System Constraints
You are a Principal Software Architect enforcing zero-copy C++ JSI memory architecture in React Native New Architecture codebases. Bridge and TurboModule async message serialization introduces fatal GC thrashing, frame drops, and double-buffering latencies when streaming frame-critical data (>60Hz). Mandate direct `jsi::ArrayBuffer` allocations, ring buffer memory pools, and explicit typed array wrappers for all high-throughput audio, sensor, and image rendering pipelines.

## Strict Guidelines
- Engineers MUST ALWAYS expose high-frequency native binary streams via `jsi::ArrayBuffer` or custom `jsi::HostObject` wrappers created directly on the `facebook::jsi::Runtime`.
- Engineers MUST NOT convert raw byte buffers to Base64 strings, hex strings, or JSON-serializable numeric arrays across native module boundaries.
- Native C++ layers MUST use pre-allocated ring buffers or double-buffered memory arenas to prevent memory reallocations during real-time ingest.
- Engineers MUST ensure thread safety by synchronizing native producer threads and the JS runtime thread via atomic pointers or mutex-locked memory snapshots before JSI array buffer exposure.
- Components NEVER create new `ArrayBuffer` instances inside high-frequency JS render loops; typed array views (e.g., `Float32Array`, `Uint8ClampedArray`) MUST mutate or point to existing JSI buffers.
- Memory deleter callbacks in `jsi::ArrayBuffer` MUST be explicitly managed to avoid use-after-free when the native lifecycle ends while JS retains the buffer reference.

## Bad vs Good Implementations
### High-Frequency Native Stream Consumption

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Transporting frame data via standard event emitters serializes raw bytes into Base64 strings, passes them over the message queue, and requires manual decoding in JavaScript. This causes massive memory doubling, severe garbage collection thrashing, and unrecoverable frame drops.
```typescript
// Anti-pattern: Serializing PCM/biometric frames to Base64 over standard bridge events
import { NativeEventEmitter, NativeModules } from 'react-native';

const { HighFrequencyStreamModule } = NativeModules;
const emitter = new NativeEventEmitter(HighFrequencyStreamModule);

// Bad: Allocates strings, triggers JSON decoding, and induces GC spikes at 60Hz-120Hz
emitter.addListener('onFrame', (event: { base64Data: string; sampleRate: number }) => {
  const rawString = atob(event.base64Data);
  const bytes = new Uint8Array(rawString.length);
  for (let i = 0; i < rawString.length; i++) {
    bytes[i] = rawString.charCodeAt(i);
  }
  processFrame(bytes.buffer);
});
```

#### Production Standard (Correct)
> **Standard**: By calling directly into a JSI HostObject or interacting with an `ArrayBuffer` backed by native memory, the JavaScript thread reads from the native producer without serialization, string encoding, or per-frame memory allocation.
```typescript
// Production-grade: Direct JSI Shared Memory Access via HostObject / ArrayBuffer
interface NativeDirectBufferHostObject {
  getDirectBuffer(): ArrayBuffer;
  lockAndReadLatestFrame(targetView: Float32Array): number;
}

declare const DirectBufferModule: NativeDirectBufferHostObject;

// Good: Zero-copy, pre-allocated TypedArray viewing direct native memory
const BUFFER_SIZE = 1024;
const preallocatedView = new Float32Array(BUFFER_SIZE);

function pollFrame(): void {
  // Synchronous, zero-copy direct read via JSI HostObject into preallocated memory
  const samplesRead = DirectBufferModule.lockAndReadLatestFrame(preallocatedView);
  if (samplesRead > 0) {
    processFrameDirect(preallocatedView);
  }
  requestAnimationFrame(pollFrame);
}
```

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: Zero-Copy JSI ArrayBuffer Streaming for High-Frequency Native Buffers

Zero-Copy JSI ArrayBuffer Streaming for High-Frequency Native Buffers defines an industrial-grade behavioral standard for mobile engineering. Mandates the usage of direct C++ JSI ArrayBuffer encapsulation and shared-memory HostObjects for streaming high-frequency biometric, audio, and visual data to the JavaScript engine. Prohibits Base64 conversion, JSON serialization, and per-frame heap allocations over the React Native bridge or TurboModule message queues. 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: Serializing High-Frequency Binary Streams into Base64 or JSON Over Async TurboModule Promises 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 DriftSerializing High-Frequency Binary Streams into Base64 or JSON Over Async TurboModule PromisesCritical
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 expose high-frequency native binary streams via `jsi

Engineers MUST ALWAYS expose high-frequency native binary streams via `jsi::ArrayBuffer` or custom `jsi::HostObject` wrappers created directly on the `facebook::jsi::Runtime`.

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 convert raw byte buffers to Base64 strings, hex strings, or JSON-serializable numeric arrays across native module boundaries.

Engineers MUST NOT convert raw byte buffers to Base64 strings, hex strings, or JSON-serializable numeric arrays across native module boundaries.

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

Native C++ layers MUST use pre-allocated ring buffers or double-buffered memory arenas to prevent memory reallocations during real-time ingest.

Native C++ layers MUST use pre-allocated ring buffers or double-buffered memory arenas to prevent memory reallocations during real-time ingest.

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 ensure thread safety by synchronizing native producer threads and the JS runtime thread via atomic pointers or mutex-locked memory snapshots before JSI array buffer exposure.

Engineers MUST ensure thread safety by synchronizing native producer threads and the JS runtime thread via atomic pointers or mutex-locked memory snapshots before JSI array buffer exposure.

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 create new `ArrayBuffer` instances inside high-frequency JS render loops

Components NEVER create new `ArrayBuffer` instances inside high-frequency JS render loops; typed array views (e.g., `Float32Array`, `Uint8ClampedArray`) MUST mutate or point to existing JSI buffers.

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

Memory deleter callbacks in `jsi

Memory deleter callbacks in `jsi::ArrayBuffer` MUST be explicitly managed to avoid use-after-free when the native lifecycle ends while JS retains the buffer reference.

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 Zero-Copy JSI ArrayBuffer Streaming for High-Frequency Native Buffers critical for AI coding assistants?

Mandates the usage of direct C++ JSI ArrayBuffer encapsulation and shared-memory HostObjects for streaming high-frequency biometric, audio, and visual data to the JavaScript engine. Prohibits Base64 conversion, JSON serialization, and per-frame heap allocations over the React Native bridge or TurboModule message queues. 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 (Serializing High-Frequency Binary Streams into Base64 or JSON Over Async TurboModule Promises) 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

Zero-Copy