Skip to content

iOS dev packager WebSocket (RCTReconnectingWebSocket) multiplies its reconnect timers when the Metro port answers with an HTTP error instead of refusing, exhausting the host's ephemeral ports #58988

Open
samirakash248-max/react-native
#1

Description

@philhradecs

Environment

  • React Native 0.86.3 (file unchanged on 0.87.1 and main as of 2026-10-09)
  • Expo SDK 57 dev client (expo ~57.0.25, expo-dev-client ~57.0.19), debug build
  • iOS Simulator, iPhone 17, iOS 26.5 runtime, Xcode 27.0, macOS 27.0 host
  • How the socket got attached: the dev client was launched against a Metro on
    127.0.0.1:8090. That Metro exited and the app stayed open in the simulator.
    About 20 hours later an unrelated local HTTP server (process-compose's API)
    bound port 8090. It answers GET /message?role=ios with 404, not a WebSocket upgrade.

Observed

From the simulator's unified log (log show --predicate 'process == "<app>"',
counting initial parent-flow lines to :8090 per minute):

Port state Connections per minute
Nothing listening (connection refused), for hours about 58
HTTP server answering 404, minute 1 → 4 115 → 1,289 → 3,153 → 5,806

Within five minutes the host had about 15,000 sockets in TIME_WAIT, the
ephemeral port range was exhausted, and every localhost connection on the
machine (not just the app's) failed with can't assign requested address.

Caveat: the unified log redacts URLs, so it shows the connection rate per
process, not which client made them. The other clients in the dev client were
ruled out by reading their source: InspectorPackagerConnection backs off
exponentially (2 s → 120 s cap), Expo's HMR client does not reconnect on its
own, and the dev launcher's status probe only pings Bonjour-discovered servers.
A later 45 s replay of the same 404 against the still-running app drew zero
connections: by then its reconnect timers had already stopped (cause unknown),
so the storm was not reproduced live. The curve above plus the code path below
is the evidence.

Expected

At most one pending reconnect at a time, with a delay that backs off, and the
same behaviour whether the port refuses or answers with an HTTP error. This is
what the inspector connection in the same app already does
(ReactCommon/jsinspector-modern/InspectorPackagerConnection.cpp, lines 24–26
and 351–391: a reconnectPending_ guard and doubling delay up to MAX_RECONNECT_DELAY).

Code path (packages/react-native/Libraries/WebSocket/RCTReconnectingWebSocket.m)

RCTPackagerConnection.mm builds the URL <scheme>://<host>:<port>/message?role=ios
(socketForLocation, lines 65–93) and calls [_socket start] (line 101).

  1. reconnect (lines 71–86) captures __weak SRWebSocket *socket = _socket, waits 2 s,
    then runs [weakSelf start] and if (!socket) { [weakSelf reconnect]; }.
  2. start (lines 46–56) begins with [self stop] (lines 58–64), which sets _socket = nil
    and releases the old socket. So by the time the if (!socket) check runs, the weak
    reference is nearly always nil, and the block schedules a second timer unconditionally.
  3. The new socket's failure then arrives through one of two delegate methods:
    • didFailWithError (lines 93–99) calls reconnect for every error except
      ECONNREFUSED.
    • didCloseWithCode (lines 101–108) always calls reconnect.

Per 2 s cycle, one pending timer therefore becomes two whenever the failure is
not a refused TCP connection: one from the if (!socket) re-arm, one from the
failure callback. With a refused connection the failure callback is skipped and
the timer count stays flat.

A non-Metro HTTP server is the "not refused" case. SocketRocket turns any
response code ≥ 400 into an NSError in SRWebSocketErrorDomain with code
2132 (SRWebSocket.m, _HTTPHeadersDidFinish; SRError.m,
SRHTTPErrorWithCodeDescription) and delivers it via didFailWithError.
2132 != ECONNREFUSED, so step 3 re-arms. That matches the table: flat while
refused, doubling once something answered.

Unverified detail: the flat phase measured about one connection per second,
while a single surviving timer predicts one per 2 s. Two timers surviving the
refused phase would explain it, but that was not checked.

Minimal reproduction (as far as the evidence supports)

  1. Debug build of any RN 0.86 iOS app (Expo dev client or bare). Run Metro on a
    fixed port, launch the app so the packager socket connects, then stop Metro.
    Leave the app open. Verified on 2026-10-11 as the state that produced the log.
  2. Start any HTTP server that answers 404 on that port, e.g.
    python3 -m http.server 8081. Unverified as a repro: the observed trigger was
    process-compose's API server; a plain 404 server should behave the same, since
    SocketRocket only looks at the status code.
  3. Count connections to the port per minute, e.g.
    xcrun simctl spawn booted log stream --predicate 'process == "<app>"' | grep -c ...
    or netstat -an | grep -c ':8081 .*TIME_WAIT'. Expect the rate to roughly double
    every few seconds instead of staying near one per 2 s.

Suggested fix (a sketch, not a patch)

  • Drop the if (!socket) [weakSelf reconnect] re-arm in reconnect. The failure
    callbacks already re-arm, and start always releases the old socket, so the
    check does not do what it appears to do.
  • Guard reconnect with a single _reconnectPending flag, cleared when the timer
    fires, mirroring InspectorPackagerConnection::Impl::reconnect.
  • Back off exponentially from 2 s to a cap, like the inspector's 120 s.
  • Possibly treat ECONNREFUSED the same as other failures once the backoff
    exists; the special case only hides the double re-arm today.

Activity

  1. react-native-bot commented on Oct 11, 2026

    @react-native-bot
    Collaborator

    Warning

    Missing reproducer: We could not detect a reproducible example in your issue report. Reproducers are mandatory and we can accept only one of those as a valid reproducer:


    You can read more about about it on our website: How to report a bug.

  2. added a commit that references this issue on Oct 14, 2026
  3. Jneck commented on Oct 28, 2026

    @Jneck

    I hit the same ephemeral-port exhaustion on a different setup, and I was able to attribute the connections to RCTReconnectingWebSocket directly. Notably, in my case Metro was running normally the whole time. No foreign HTTP server was involved, so the trigger seems wider than a port answering with 404.

    Environment

    • React Native 0.88.0 (RCTReconnectingWebSocket.m is unchanged from main)
    • Expo SDK 58 dev client (expo 58.0.16, expo-dev-client 58.0.14), debug build
    • iOS Simulator, iPhone 17 Pro, iOS 26.5 runtime, Xcode 26.6, macOS 26.6.2
    • Metro started with expo start --dev-client --lan --port 8081. It ran for about 3 days, and the app stayed open in the simulator for about 1.5 days.

    Observed

    • 16,176 sockets in TIME_WAIT, all from 192.168.0.21:<ephemeral> to 192.168.0.21:8081 (the Metro LAN address). That is nearly the whole 49152–65535 range.
    • The rate was about 36 new connections per second while ports were nearly exhausted. After ports were freed, it jumped to roughly 600 per second.
    • With Metro stopped and nothing listening on 8081, the iOS app made no connection attempts during a 20-second window. The storm only ran while something accepted the TCP connection.

    Attribution

    1. I replaced Metro with a logging TCP proxy on 8081 that forwarded to a fresh Metro on 8082. In 12 seconds the iOS app opened 7,357 TCP connections and sent zero bytes on any of them: no HTTP request and no WebSocket upgrade. The Android emulator attached to the same Metro behaved normally, sending regular /message and /inspector/* upgrades.
    2. I attached lldb to the running app with breakpoints on CFStreamCreatePairWithSocketToHost and nw_connection_start. Every hit had the same stack:
    CFStreamCreatePairWithSocketToHost
    -[SRProxyConnect _initializeStreams]            SRProxyConnect.m:313
    -[SRProxyConnect _openConnection]               SRProxyConnect.m:285
    -[SRProxyConnect _configureProxy]               SRProxyConnect.m:182
    -[SRProxyConnect openNetworkStreamWithCompletion:] SRProxyConnect.m:85
    -[SRWebSocket open]                             SRWebSocket.m:341
    -[RCTReconnectingWebSocket start]               RCTReconnectingWebSocket.m:55
    __37-[RCTReconnectingWebSocket reconnect]_block_invoke  RCTReconnectingWebSocket.m:81
    _dispatch_client_callout
    ...
    _dispatch_main_queue_callback_4CF
    

    This matches the analysis in the issue and in #59055. if (!socket) checks the previous socket, which start has just released, so each timer re-arms itself unconditionally. Every close or failure delegate callback then adds another timer. With many timers firing at once, each start closes the socket the previous one just opened before the handshake is written. That explains the zero-byte connections, and since the client closes first, the TIME_WAIT entries pile up on the client's ephemeral ports.

    I didn't capture the exact event that first multiplied the timers in my session. The app had been open across Mac sleep and network changes for about 1.5 days. Once there are N timers, though, the zero-byte churn happens even against a healthy Metro.

    I'm happy to test #59055 on this setup if that would help.

  4. react-native-bot commented on Nov 21, 2026

    @react-native-bot
    Collaborator

    This issue is waiting for author's feedback since 24 days. Please provide the requested feedback or this will be closed in 7 days.

  5. added
    StaleThere has been a lack of activity on this issue and it may be closed soon.
    on Nov 21, 2026
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

    Needs: Author FeedbackNeeds: ReproThis issue could be improved with a clear list of steps to reproduce the issue.StaleThere has been a lack of activity on this issue and it may be closed soon.

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions