Skip to content

[iOS] RCTNetworkTask keeps the full response of incremental text requests in memory #60249

Backlog

Description

@rexxars

Description

On iOS, RCTNetworkTask keeps all the data of an incremental text request in memory until the request ends. For a response that stays open, for example a stream of server-sent events, memory use increases for as long as the stream is open.

An incremental text request is a request that RCTNetworking sends with incrementalUpdates set to true and responseType set to text. XMLHttpRequest sends this type of request when JavaScript listens for progress or readystatechange events. EventSource implementations for React Native use it to read a stream as it arrives.

Cause

-[RCTNetworkTask URLRequest:didReceiveData:] appends each chunk to its response buffer (_data). Then it gives the same chunk to the incrementalDataBlock. For an incremental text request, RCTNetworking sends each chunk to JavaScript from that block.

At completion, RCTNetworking uses the response buffer of an incremental text request for two things only:

  • The encodedDataLength that it reports to the DevTools network reporter.
  • A text response handler (RCTNetworking+Internal.h), if one handles the request.

Android does not keep the response. NetworkingModule.readWithProgress reads the body in a loop and sends each decoded chunk to JavaScript.

Related issues

#41651 reported a crash, NSMallocException: Failed to grow buffer, at [_data appendData:] in this method. The fix for that issue (3c4517f) catches the exception and fails the request with "Request's received data too long.". The response buffer did not change. As a result, a stream that stays open for long enough now fails with a network error, instead of a crash.

In debug builds, the DevTools network reporter also keeps the response text (see #60187). This issue is only about the response buffer in RCTNetworkTask, which is also in release builds.

Proposed fix

I have a change on a branch, and I can open a pull request for it. The default behavior of RCTNetworkTask stays the same:

  • RCTNetworkTask gets a buffersResponseData property. The default value is YES. If the value is NO, the task counts the received bytes for the progress values, but it does not append the chunks to _data. The completion block then gets nil data.
  • If no text response handler handles an incremental text request, RCTNetworking sets buffersResponseData to NO for that request.
  • The incremental data block keeps the number of received bytes. This gives the DevTools network reporter the correct encodedDataLength.

RCTImageLoader and the other users of RCTNetworkTask do not set the property, so they still get the full response.

With the change, the task keeps none of the response:

  • In a test that held a 32 MiB response open, the task kept all 32 MiB before the change, in 35.4 MiB of allocated capacity. After the change, it kept 0 bytes.
  • In a five-minute run of the reproducer, the stream sent 16.1 MiB. The largest NSMutableData allocation in the app was 16.5 KiB.

Branch: rexxars/react-native@main...fix/ios-incremental-text-buffering

Steps to reproduce

The reproducer calls Networking directly, not XMLHttpRequest. XMLHttpRequest also keeps responseText in JavaScript, and that growth hides the native growth.

The reproducer updates its counter every 10 seconds - initially I rendered on every event, which created short-lived JavaScript and Fabric objects. Until garbage collection removes them, they also increase the memory use.

  1. Replace packages/rn-tester/js/examples/Playground/RNTesterPlayground.js with the file below. The same file is on the reproducer branch (link below).
  2. Run RNTester on an iOS simulator. Then open the Playground example.
  3. After five minutes, examine the heap of the app, for example with the Allocations instrument or heap.

The file opens the Wikimedia stream of recent changes. This stream sends a server-sent event for each edit on a Wikimedia wiki, and it does not end.

Expected result: No allocation increases with the stream.

Actual result: The backing storage of an NSMutableData in RCTNetworkTask increases for as long as the stream is open. In a five-minute run, the stream sent 17.1 MiB, and this allocation was 25.0 MiB.

Do not use the memory gauge in Xcode for this test. When the buffer grows, realloc moves it with vm_copy. The copied pages do not count in the memory footprint until the process reads them again. As a result, the footprint decreases abruptly at some points, but the buffer still keeps all the data. In one run, reading the retained pages increased the footprint by 11.4 MiB, with no new data.

RNTesterPlayground.js:

/**
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow strict-local
 * @format
 */

import type {RNTesterModuleExample} from '../../types/RNTesterTypes';

import RNTesterText from '../../components/RNTesterText';
import * as React from 'react';
import {useEffect, useState} from 'react';
import {Networking, StyleSheet, View} from 'react-native';

// Wikimedia's stream of recent changes. It sends an event for each edit
const URL = 'https://stream.wikimedia.org/v2/stream/recentchange';

function Playground() {
  const [received, setReceived] = useState(0);

  useEffect(() => {
    let requestId: ?number = null;
    let bytes = 0;
    const subscription = Networking.addListener(
      'didReceiveNetworkIncrementalData',
      ([id, , progress]) => {
        if (id === requestId) {
          bytes = progress;
        }
      },
    );

    // Update the counter every 10 seconds, not on every event. Rendering on every event creates
    // enough short-lived garbage to hide the memory growth that this reproducer is about.
    const interval = setInterval(() => setReceived(bytes), 10_000);

    // An incremental text request, the same as XMLHttpRequest sends when it has a `progress`
    // listener. JavaScript keeps none of the response here.
    Networking.sendRequest(
      'GET',
      'playground', // Tracking name
      URL,
      {Accept: 'text/event-stream'},
      '', // Request body data
      'text', // Response type
      true, // Incremental updates
      0, // Timeout
      id => { // Callback
        requestId = id;
      },
      false, // withCredentials
    );

    return () => {
      clearInterval(interval);
      subscription.remove();
      if (requestId != null) {
        Networking.abortRequest(requestId);
      }
    };
  }, []);

  return (
    <View style={styles.container}>
      <RNTesterText>
        Received {(received / 1024 / 1024).toFixed(1)} MB
      </RNTesterText>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    padding: 10,
  },
});

export default {
  title: 'Playground',
  name: 'playground',
  description: 'Test out new features and ideas.',
  render: (): React.Node => <Playground />,
} as RNTesterModuleExample;

React Native Version

0.88.1. The same code is on main.

Affected Platforms

Runtime - iOS

Output of npx @react-native-community/cli info

System:
  OS: macOS 26.6.2
  CPU: (16) arm64 Apple M3 Max
  Memory: 1.62 GB / 48.00 GB
  Shell:
    version: "5.9"
    path: /bin/zsh
Binaries:
  Node:
    version: 24.15.0
    path: ~/.local/share/mise/installs/node/24.15.0/bin/node
  Yarn: Not Found
  npm:
    version: 12.0.1
    path: ~/.local/share/mise/installs/node/24.15.0/bin/npm
  Watchman: Not Found
Managers:
  CocoaPods:
    version: 1.17.0
    path: /opt/homebrew/bin/pod
SDKs:
  iOS SDK:
    Platforms:
      - DriverKit 27.2
      - iOS 27.2
      - macOS 27.2
      - tvOS 27.2
      - visionOS 27.2
      - watchOS 27.2
  Android SDK: Not Found
IDEs:
  Android Studio: Not Found
  Xcode:
    version: 27.2/27B52
    path: /usr/bin/xcodebuild
Languages:
  Java: Not Found
  Ruby:
    version: 4.0.9
    path: /opt/homebrew/bin/ruby
npmPackages:
  "@react-native-community/cli": Not Found
  react: Not Found
  react-native: Not Found
  react-native-macos: Not Found
npmGlobalPackages:
  "*react-native*": Not Found
Android:
  hermesEnabled: false
  newArchEnabled: false
iOS:
  hermesEnabled: true
  newArchEnabled: true

Stacktrace or Logs

The stack trace from #41651 (React Native 0.72.6), before the fix that catches the exception:


Fatal Exception: NSMallocException
3  CoreFoundation   __CFReallocationFailed
4  CoreFoundation   __CFSafelyReallocate
5  Foundation       _NSMutableDataGrowBytes
6  Foundation       -[NSConcreteMutableData appendBytes:length:]
9  Foundation       -[NSConcreteMutableData appendData:]
10 CommonApp_name   -[RCTNetworkTask URLRequest:didReceiveData:] + 168 (RCTNetworkTask.mm:168)
11 CommonApp_name   -[RCTHTTPRequestHandler URLSession:dataTask:didReceiveData:] + 171 (RCTHTTPRequestHandler.mm:171)


On current versions, the request fails with "Request's received data too long." instead.

MANDATORY Reproducer

https://github.com/rexxars/react-native/blob/repro/ios-incremental-text-buffering/packages/rn-tester/js/examples/Playground/RNTesterPlayground.js

Screenshots and Videos

No response

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions