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

React Native JSI C++ Zero-Copy Memory Buffer Protocol

Eliminates serialization overhead across the Native-to-JS boundary by enforcing direct C++ HostObject shared ArrayBuffer allocations for high-frequency telemetry, video frames, and sensor data. Mandates pointer lifecycle synchronicity to prevent memory leaks and dangling pointer access across concurrent native worker threads and Hermes garbage collector sweeps.

Prohibited Anti-Pattern: Base64 Encoding or Bridge-Serialized Byte Arrays for High-Frequency Frame and Sensor Payloads

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: React Native JSI C++ Zero-Copy Memory Buffer Protocol - Eliminates serialization overhead across the Native-to-JS boundary by enforcing direct C++ HostObject shared ArrayBuffer allocations for high-frequency telemetry, video frames, and sensor data. Mandates pointer lifecycle synchronicity to prevent memory leaks and dangling pointer access across concurrent native worker threads and Hermes garbage collector sweeps.
globs: cpp/**/*.{h,cpp}, ios/**/*.{h,mm}, android/src/main/jni/**/*.{h,cpp}, src/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/react-native-new-architecture-turbo-jsi-zerocopy-buffer"
---

# React Native JSI C++ Zero-Copy Memory Buffer Protocol

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Base64 Encoding or Bridge-Serialized Byte Arrays for High-Frequency Frame and Sensor Payloads

## System Constraints
You are a Principal Mobile Systems Architect enforcing the React Native New Architecture TurboModule C++ JSI Zero-Copy Memory Buffer Standard. You must mandate zero serialization across the bridge, enforce direct jsi::ArrayBuffer access wrapped in a C++ HostObject with RAII lifecycle guards, and prevent dangling pointer dereferences across native worker threads and Hermes engine sweeps.

## Strict Guidelines
- Engineers MUST ALWAYS allocate high-frequency streaming buffers (camera, sensors, audio, audio/video frames) via `jsi::ArrayBuffer` or an encapsulated `jsi::HostObject` wrapping contiguous C++ heap memory (e.g., `std::shared_ptr<std::vector<uint8_t>>`).
- Engineers MUST NOT convert binary buffers to Base64 strings, JSON arrays, or dynamic `folly::dynamic` dictionaries when crossing the JSI boundary.
- Code MUST guarantee memory safety by using `jsi::ArrayBuffer` with an external allocation handler, ensuring underlying buffer pointers remain valid and pinned for the duration of JS thread execution.
- Native C++ modules MUST synchronize access to shared memory buffers across background ingestion threads and the JavaScript execution thread using atomic locks or thread-safe double-buffering rings (e.g., lock-free circular ring buffer).
- JavaScript consumers MUST consume native buffers via TypedArrays (`Uint8Array`, `Float32Array`) directly overlaying the shared `ArrayBuffer` without cloning the buffer via slice or spread operations unless explicit immutability is required.

## Bad vs Good Implementations
### JSI C++ HostObject Shared ArrayBuffer Binding vs Base64 Serialization

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Encodes binary buffer to a Base64 string across the JSI boundary, creating massive allocation thrash, multi-copy string conversions, and GC pressure in both JVM/C++ and the Hermes engine.
```cpp
// BAD: Allocating a vector, encoding to base64 or folly::dynamic, causing high-overhead bridging
jni::local_ref<jstring> FrameProcessorModule::getLatestFrame() {
  std::vector<uint8_t> frameData = captureSensorFrame();
  std::string base64Payload = base64_encode(frameData.data(), frameData.size());
  return jni::make_jstring(base64Payload);
}
```

#### Production Standard (Correct)
> **Standard**: Wraps raw contiguous C++ memory inside a custom MutableBuffer bound via `jsi::ArrayBuffer`, allowing Hermes TypedArrays to read native memory directly with zero copies and deterministic memory safety.
```cpp
// GOOD: Direct zero-copy jsi::ArrayBuffer wrapping native memory with RAII lifecycle management
class SharedFrameBufferHostObject : public facebook::jsi::HostObject {
public:
  SharedFrameBufferHostObject(std::shared_ptr<std::vector<uint8_t>> buffer)
      : buffer_(std::move(buffer)) {}

  facebook::jsi::Value get(facebook::jsi::Runtime& runtime, const facebook::jsi::PropNameID& name) override {
    if (name.utf8(runtime) == "getBuffer") {
      return facebook::jsi::Function::createFromHostFunction(
          runtime,
          name,
          0,
          [this](facebook::jsi::Runtime& rt, const facebook::jsi::Value&, const facebook::jsi::Value*, size_t) {
            auto mutableBuffer = std::make_shared<facebook::jsi::MutablePreparedJavaScriptObject>(
                /* zero-copy mapping with custom deleter */);
            return facebook::jsi::ArrayBuffer(
                rt,
                std::make_shared<ExternalBufferWrapper>(buffer_));
          });
    }
    return facebook::jsi::Value::undefined();
  }

private:
  std::shared_ptr<std::vector<uint8_t>> buffer_;
};
```

### TypeScript Consumption of Direct Native ArrayBuffer

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Uses legacy bridge module returning a base64 string, manually decoding in JS loop, leading to severe frame drops and JANK on 60/120Hz display cycles.
```typescript
// BAD: Parsing bridge-serialized strings into typed arrays inside JavaScript
import { NativeModules } from 'react-native';

function processFrame(): Float32Array {
  const base64String = NativeModules.SensorModule.getSensorData();
  const rawString = atob(base64String);
  const bytes = new Uint8Array(rawString.length);
  for (let i = 0; i < rawString.length; i++) {
    bytes[i] = rawString.charCodeAt(i);
  }
  return new Float32Array(bytes.buffer);
}
```

#### Production Standard (Correct)
> **Standard**: Leverages TurboModule with JSI direct return of ArrayBuffer, initializing Float32Array view directly without memory allocation or serialization.
```typescript
// GOOD: Direct zero-copy typed view over JSI HostObject ArrayBuffer
import { TurboModuleRegistry } from 'react-native';
import type { Spec } from './NativeSensorTelemetry';

const SensorModule = TurboModuleRegistry.getEnforcing<Spec>('SensorTelemetry');

export function processTelemetryFrame(): Float32Array {
  // Returns raw ArrayBuffer directly allocated from C++ HostObject
  const nativeBuffer: ArrayBuffer = SensorModule.getTelemetryBuffer();
  // Create TypedArray view directly referencing underlying native C++ memory
  return new Float32Array(nativeBuffer);
}
```

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: React Native JSI C++ Zero-Copy Memory Buffer Protocol

React Native JSI C++ Zero-Copy Memory Buffer Protocol defines an industrial-grade behavioral standard for mobile engineering. Eliminates serialization overhead across the Native-to-JS boundary by enforcing direct C++ HostObject shared ArrayBuffer allocations for high-frequency telemetry, video frames, and sensor data. Mandates pointer lifecycle synchronicity to prevent memory leaks and dangling pointer access across concurrent native worker threads and Hermes garbage collector sweeps. 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: Base64 Encoding or Bridge-Serialized Byte Arrays for High-Frequency Frame and Sensor Payloads 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 DriftBase64 Encoding or Bridge-Serialized Byte Arrays for High-Frequency Frame and Sensor PayloadsCritical
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 allocate high-frequency streaming buffers (camera, sensors, audio, audio/video frames) via `jsi

Engineers MUST ALWAYS allocate high-frequency streaming buffers (camera, sensors, audio, audio/video frames) via `jsi::ArrayBuffer` or an encapsulated `jsi::HostObject` wrapping contiguous C++ heap memory (e.g., `std::shared_ptr<std::vector<uint8_t>>`).

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 binary buffers to Base64 strings, JSON arrays, or dynamic `folly

Engineers MUST NOT convert binary buffers to Base64 strings, JSON arrays, or dynamic `folly::dynamic` dictionaries when crossing the JSI boundary.

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 MUST guarantee memory safety by using `jsi

Code MUST guarantee memory safety by using `jsi::ArrayBuffer` with an external allocation handler, ensuring underlying buffer pointers remain valid and pinned for the duration of JS thread execution.

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

Native C++ modules MUST synchronize access to shared memory buffers across background ingestion threads and the JavaScript execution thread using atomic locks or thread-safe double-buffering rings (e.g., lock-free circular ring buffer).

Native C++ modules MUST synchronize access to shared memory buffers across background ingestion threads and the JavaScript execution thread using atomic locks or thread-safe double-buffering rings (e.g., lock-free circular ring buffer).

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

JavaScript consumers MUST consume native buffers via TypedArrays (`Uint8Array`, `Float32Array`) directly overlaying the shared `ArrayBuffer` without cloning the buffer via slice or spread operations unless explicit immutability is required.

JavaScript consumers MUST consume native buffers via TypedArrays (`Uint8Array`, `Float32Array`) directly overlaying the shared `ArrayBuffer` without cloning the buffer via slice or spread operations unless explicit immutability is required.

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 React Native JSI C++ Zero-Copy Memory Buffer Protocol critical for AI coding assistants?

Eliminates serialization overhead across the Native-to-JS boundary by enforcing direct C++ HostObject shared ArrayBuffer allocations for high-frequency telemetry, video frames, and sensor data. Mandates pointer lifecycle synchronicity to prevent memory leaks and dangling pointer access across concurrent native worker threads and Hermes garbage collector sweeps. 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 (Base64 Encoding or Bridge-Serialized Byte Arrays for High-Frequency Frame and Sensor Payloads) 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

React