Network Tuning

View Markdown

Last edited on 2026-06-16

Mini Program and the Mini Game Network-related APIs use the same approach, so we collectively refer to them as Network Interfaces.

Composition of Network Interfaces

Network interfaces primarily include four types:

  • request
  • download
  • upload
  • websocket

Implementation on Different Platforms

Android

  • The request interface uses the underlying component (cronet) wrapped around the network-related parts of Chromium from client version 7.0.10 onwards. Previous versions use the HttpURLConnection system component. (System components depend on system implementation, which may cause platform compatibility issues. We recommend debugging with newer versions of WeChat.)
  • The download interface uses the cronet component from client version 7.0.12 onwards. Previous versions use the HttpURLConnection component.
  • The upload interface currently still uses the HttpURLConnection component.
  • The websocket interface uses the underlying WeChat component wcwss from client version 7.0.4 onwards, and its calling performance was optimized in version 7.0.10.

iOS

  • The request/download interfaces use the Cronet component starting from client version 8.0.3. Earlier versions used the NSURLSession system component.
  • The upload interface currently still uses the NSURLSession component.
  • The websocket interface uses WeChat's underlying wcwss component starting from client version 7.0.20. Earlier versions used the SRWebSocket component.

Easily Misunderstood Concepts

success/fail/complete callbacks

  • For the request/download/upload interfaces, the callbacks represent the final result of the network request.
  • For the WebSocket interfaces, the callbacks only represent the result of the interface call. You should listen for specific events to obtain the actual network connection/request status.

wx.sendSocketMessage/SocketTask.send

In the early stages, a single Mini Program was only allowed to maintain one WebSocket connection at a time. Therefore, the WebSocket-related APIs in older versions of the Base Library were directly designed on the wx object:

  • wx.connectSocket
  • wx.onSocketOpen
  • wx.sendSocketMessage
  • wx.onSocketMessage
  • wx.closeSocket
  • wx.onSocketClose
  • wx.onSocketError

Now, a single Mini Program is allowed to maintain multiple WebSocket connections simultaneously. The original API design could not meet this demand. As a result, the Base Library introduced the concept of SocketTask in version 1.7.0 and later, allowing multiple connections to be managed through different instances:

  • wx.connectSocket
  • SocketTask.onOpen
  • SocketTask.send
  • SocketTask.onMessage
  • SocketTask.close
  • SocketTask.onClose
  • SocketTask.onError

In the new design, the original wx.connectSocket API is used to create an instance (new SocketTask). Therefore, except for wx.connectSocket, you should not use any other WebSocket APIs attached to wx. After calling wx.connectSocket, please synchronously listen for SocketTask.onOpen immediately, otherwise you might miss the onOpen notification.

Performance Analysis

Android

  • Starting from client version 7.0.12, the request/download interfaces provide profile information in the callback, detailing the elapsed time for key points during the network connection process. The specific meanings are as follows:
Name Description
redirectStart The time when the first HTTP redirect occurs. Only redirects within the same domain are counted; otherwise, the value is 0.
redirectEnd The time when the last HTTP redirect completes. Only redirects within the same domain are counted; otherwise, the value is 0.
fetchStart The time when the component is ready to fetch resources using HTTP requests. This occurs before checking the local cache.
domainLookUpStart The time when the DNS domain lookup starts. If a local cache (i.e., no DNS lookup) or persistent connection is used, this value equals fetchStart.
domainLookUpEnd The time when the DNS domain lookup completes. If a local cache (i.e., no DNS lookup) or persistent connection is used, this value equals fetchStart.
connectStart The time when TCP starts establishing the connection. If it is a persistent connection, this value equals fetchStart. Note: If a transport layer error occurs and a new connection is established, this reflects the start time of the new connection.
connectEnd The time when TCP completes establishing the connection (handshake finished). If it is a persistent connection, this value equals fetchStart. Note: If a transport layer error occurs and a new connection is established, this reflects the completion time of the new connection. Note that the handshake includes the establishment of secure connections and SOCKS authorization.
SSLconnectionStart The time when the SSL connection starts. If it is not a secure connection, the value is 0.
SSLconnectionEnd The time when the SSL connection is established. If it is not a secure connection, the value is 0.
requestStart The time when the HTTP request starts reading the actual document (connection established), including reading from the local cache. If the connection is re-established due to an error, this also reflects the time of the new connection.
requestEnd The time when the HTTP request finishes reading the actual document.

| responseStart | The time when the HTTP response reception starts (the first byte is received), including reading from local cache | | responseEnd | The time when the HTTP response reception is fully completed (the last byte is received), including reading from local cache | | rtt | The real-time RTT during the connection process of the current request | | estimate_nettype | The estimated network status: unknown, offline, slow 2g, 2g, 3g, 4g, last/0, 1, 2, 3, 4, 5, 6 | | httpRttEstimate | The RTT of the current network estimated by the protocol layer based on multiple requests (for reference only) | | transportRttEstimate | The RTT of the current network estimated by the transport layer based on multiple requests (for reference only) | | downstreamThroughputKbpsEstimate | The estimated download throughput in kbps for the current network, based on the RTT, response status of recent requests, and the current network conditions | | throughputKbps | The actual download throughput in kbps for the current network, calculated based on the actual data of this request: bytes received from the start of the request to its end * 8 / request duration | | peerIP | The target IP of the current request | | port | The target port of the current request | | protocol | The protocol used by the current request | | socketReused | Whether the connection was reused | | sendBytesCount | The number of bytes sent |

| receivedBytedCount | Number of bytes received |

The entire request pipeline is DNS -> Connect -> SSL -> request -> response; the rtt in the table is the real-time rtt during the connection process, updated at each stage, while httpRttEstimate and transportRttEstimate are comprehensive values calculated based on previous requests

  • Starting from client version 7.0.12, the WebSocket API provides profile information in the onOpen callback, detailing the time consumption of key milestones during the network connection process. The specific meanings are as follows
Name Description
fetchStart The time when the component is ready to use SOCKET to establish a request. This occurs before checking the local cache
domainLookUpStart The time when DNS domain lookup starts. If local cache is used (i.e., no DNS lookup) or a persistent connection is used, this value is equal to fetchStart
domainLookUpEnd The time when DNS domain lookup completes. If local cache is used (i.e., no DNS lookup) or a persistent connection is used, this value is equal to fetchStart
connectStart The time when establishing a connection starts. If it is a persistent connection, this value is equal to fetchStart. Note that if an error occurs at the transport layer and a new connection is re-established, the time shown here is the start time of the new connection
connectEnd The time when connection establishment completes (handshake finished). If it is a persistent connection, this value is equal to fetchStart. Note that if an error occurs at the transport layer and a new connection is re-established, the time shown here is the completion time of the new connection. Note that handshake completion includes the establishment of secure connections and successful SOCKS authorization
rtt The duration of a single connection, including connect and tls
handshakeCost Handshake duration
cost The duration from the upper-layer request to the response

The entire request pipeline is DNS -> Connect; in the table, connectEnd - connectStart represents the pure TCP connection duration, and domainEnd - domainStart represents the domain resolution duration; the durations of the above two steps plus handshakeCost represent the total duration of a single connection request

iOS

  • The profile capability is available via the request/download interfaces starting from client version 8.0.3
  • The profile capability is available via the websocket interface starting from client version 7.0.20

Tips

  • When encountering network issues, in addition to checking network connectivity, you can analyze the user's current network conditions using rtt to dynamically adjust timeout parameters.
  • Network requests provide an enableProfile parameter, which defaults to true. You can set it to false to disable this feature.

Optimization Suggestions

Switching Between Foreground and Background

Mini Program 5 seconds after switching to the background, network requests will be interrupted. Developers will receive an interrupted callback and should implement appropriate compatibility logic.

Network Status Changes

When the user's network status changes, a notification is sent via the wx.onNetworkStatusChange event. Since many network issues are caused by disconnections, this event allows you to provide better prompts to users.

Network Fluctuation Changes

Starting from Base Library version 2.19.0, wx.onNetworkWeakChange provides notifications for network fluctuation status changes. Many timeout issues are caused by users being in a weak network environment. This event can be used to provide better prompts to users.

A weak network state is determined if any of the following three conditions occurs within the last eight network requests:

  • Three or more connection timeouts
  • RTT exceeding 400 three times
  • Three or more packet losses

The notification rule for the weak network event is: notify immediately when the weak network status changes; if the status remains unchanged, notify at most once within 30 seconds.

request/download New Protocol

Starting from Android 7.0.12 / iOS 8.0.3, the following three new parameters are provided:

Name Description
enableHttp2 Attempt to use the Http2 protocol if supported by the backend
enableQuic Attempt to use the Quic protocol if supported by the backend
enableCache Cache content; prioritize reading local content for identical requests

H2 connections are faster, and support is recommended. Note that h2 headers must be all lowercase. Ensure your code logic accounts for this before enabling the enableHttp2 switch.

perMessageDeflate

Compression parameters are currently fully supported on both Android and iOS.

Troubleshooting

Error Return Rules for Different Platforms

Android

For the error returns of cronet, please refer to: https://chromium.googlesource.com/chromium/src/+/master/net/base/net_error_list.h

Common errors for WebSocket interfaces

Name Meaning
Underlying Transport Error Exception, mostly likely caused by network issues
Timer Expired Timeout, weak network or no network
The total timed out Timeout, weak network or no network
TLS handshake failed TLS negotiation failed
TLS handshake timed TLS negotiation timeout, retry is recommended
Invalid HttpCode Server configuration error

iOS

For error returns in cronet, refer to the Android section.

The upload process generally returns messages in Chinese along with kcferrordomaincfnetwork. You can search for specific error codes and their corresponding descriptions on the official Apple Developer website to assist with analysis and resolution.

Issue with Slow IPv6 Performance

Android's HttpURLConnection attempts each IP address sequentially in accordance with RFC 3484. In this scenario, IPv6 is prioritized. However, if the system times out while attempting an IPv6 connection, it falls back to attempting IPv4 in sequence. Although the request may eventually complete within the configured 60-second timeout, the overall duration is extended, resulting in significantly long request times for the request API. This issue has been resolved in client version 7.0.10 after switching to Cronet.

Certificate Issues

Notes regarding certificates are already documented in the official guide.

  1. Certificate expiration or invalidity

Validation can be performed using https://myssl.com/ssl.html or other online tools. However, due to compatibility issues on Android devices, validation results do not guarantee effectiveness across all Android devices.

  1. Incomplete certificate chain

Android devices may not have the complete set of root certificates. If the server uses an intermediate certificate and the corresponding root certificate cannot be found on the Android device, relevant SSL errors will occur. In this case, the server must be configured with a complete certificate chain.

  1. wss protocol failing on port 80

Port 80 is associated with HTTP, which by default does not perform certificate validation. The wss protocol should use port 443.

URL Not in Domain List

The requested URL is not in the domain list. If you encounter this issue, there are several possible reasons:

  1. The requested URL is not included in the domain list configured for the Mini Program
  2. The URL after redirection is not included in the domain list
  3. The port for the WebSocket request is not configured
  4. The configured domain has not taken effect (extremely low probability)

network is down

iOS 14 introduces a new Local Network toggle. If this toggle is turned off, the local area network (LAN) becomes unreachable, and system APIs return the error "network is down." As the system does not currently provide an API to detect the status of this toggle, developers must prompt users to enable the permission based on the error message.